Index: node_modules/@reduxjs/toolkit/LICENSE
===================================================================
--- node_modules/@reduxjs/toolkit/LICENSE	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/LICENSE	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Mark Erikson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
Index: node_modules/@reduxjs/toolkit/README.md
===================================================================
--- node_modules/@reduxjs/toolkit/README.md	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/README.md	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,110 @@
+# Redux Toolkit
+
+![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/reduxjs/redux-toolkit/tests.yml?style=flat-square)
+[![npm version](https://img.shields.io/npm/v/@reduxjs/toolkit.svg?style=flat-square)](https://www.npmjs.com/package/@reduxjs/toolkit)
+[![npm downloads](https://img.shields.io/npm/dm/@reduxjs/toolkit.svg?style=flat-square&label=RTK+downloads)](https://www.npmjs.com/package/@reduxjs/toolkit)
+
+**The official, opinionated, batteries-included toolset for efficient Redux development**
+
+## Installation
+
+### Create a React Redux App
+
+The recommended way to start new apps with React and Redux Toolkit is by using [our official Redux Toolkit + TS template for Vite](https://github.com/reduxjs/redux-templates), or by creating a new Next.js project using [Next's `with-redux` template](https://github.com/vercel/next.js/tree/canary/examples/with-redux).
+
+Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.
+
+```bash
+# Vite with our Redux+TS template
+# (using the `degit` tool to clone and extract the template)
+npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
+
+# Next.js using the `with-redux` template
+npx create-next-app --example with-redux my-app
+```
+
+We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:
+
+- https://github.com/rahsheen/react-native-template-redux-typescript
+- https://github.com/rahsheen/expo-template-redux-typescript
+
+### An Existing App
+
+Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:
+
+```bash
+# NPM
+npm install @reduxjs/toolkit
+
+# Yarn
+yarn add @reduxjs/toolkit
+```
+
+The package includes a precompiled ESM build that can be used as a [`<script type="module">` tag](https://unpkg.com/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs) directly in the browser.
+
+## Documentation
+
+The Redux Toolkit docs are available at **https://redux-toolkit.js.org**, including API references and usage guides for all of the APIs included in Redux Toolkit.
+
+The Redux core docs at https://redux.js.org includes the full Redux tutorials, as well usage guides on general Redux patterns.
+
+## Purpose
+
+The **Redux Toolkit** package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:
+
+- "Configuring a Redux store is too complicated"
+- "I have to add a lot of packages to get Redux to do anything useful"
+- "Redux requires too much boilerplate code"
+
+We can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app), we can try to provide some tools that abstract over the setup process and handle the most common use cases, as well as include some useful utilities that will let the user simplify their application code.
+
+Because of that, this package is deliberately limited in scope. It does _not_ address concepts like "reusable encapsulated Redux modules", folder or file structures, managing entity relationships in the store, and so on.
+
+Redux Toolkit also includes a powerful data fetching and caching capability that we've dubbed "RTK Query". It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.
+
+## What's Included
+
+Redux Toolkit includes these APIs:
+
+- `configureStore()`: wraps `createStore` to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, add whatever Redux middleware you supply, includes `redux-thunk` by default, and enables use of the Redux DevTools Extension.
+- `createReducer()`: lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the [`immer` library](https://github.com/mweststrate/immer) to let you write simpler immutable updates with normal mutative code, like `state.todos[3].completed = true`.
+- `createAction()`: generates an action creator function for the given action type string. The function itself has `toString()` defined, so that it can be used in place of the type constant.
+- `createSlice()`: combines `createReducer()` + `createAction()`. Accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
+- `combineSlices()`: combines multiple slices into a single reducer, and allows "lazy loading" of slices after initialisation.
+- `createListenerMiddleware()`: lets you define "listener" entries that contain an "effect" callback with additional logic, and a way to specify when that callback should run based on dispatched actions or state changes. A lightweight alternative to Redux async middleware like sagas and observables.
+- `createAsyncThunk()`: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches `pending/resolved/rejected` action types based on that promise
+- `createEntityAdapter()`: generates a set of reusable reducers and selectors to manage normalized data in the store
+- The `createSelector()` utility from the [Reselect](https://github.com/reduxjs/reselect) library, re-exported for ease of use.
+
+For details, see [the Redux Toolkit API Reference section in the docs](https://redux-toolkit.js.org/api/configureStore).
+
+## RTK Query
+
+**RTK Query** is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
+
+RTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.
+
+RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
+
+```ts no-transpile
+import { createApi } from '@reduxjs/toolkit/query'
+
+/* React-specific entry point that automatically generates
+   hooks corresponding to the defined endpoints */
+import { createApi } from '@reduxjs/toolkit/query/react'
+```
+
+### What's included
+
+RTK Query includes these APIs:
+
+- `createApi()`: The core of RTK Query's functionality. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. In most cases, you should use this once per app, with "one API slice per base URL" as a rule of thumb.
+- `fetchBaseQuery()`: A small wrapper around fetch that aims to simplify requests. Intended as the recommended baseQuery to be used in createApi for the majority of users.
+- `<ApiProvider />`: Can be used as a Provider if you do not already have a Redux store.
+- `setupListeners()`: A utility used to enable refetchOnMount and refetchOnReconnect behaviors.
+
+See the [**RTK Query Overview**](https://redux-toolkit.js.org/rtk-query/overview) page for more details on what RTK Query is, what problems it solves, and how to use it.
+
+## Contributing
+
+Please refer to our [contributing guide](/CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Redux Toolkit.
Index: node_modules/@reduxjs/toolkit/dist/cjs/index.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+'use strict'
+if (process.env.NODE_ENV === 'production') {
+  module.exports = require('./redux-toolkit.production.min.cjs')
+} else {
+  module.exports = require('./redux-toolkit.development.cjs')
+}
Index: node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2387 @@
+"use strict";
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// src/index.ts
+var src_exports = {};
+__export(src_exports, {
+  ReducerType: () => ReducerType,
+  SHOULD_AUTOBATCH: () => SHOULD_AUTOBATCH,
+  TaskAbortError: () => TaskAbortError,
+  Tuple: () => Tuple,
+  addListener: () => addListener,
+  asyncThunkCreator: () => asyncThunkCreator,
+  autoBatchEnhancer: () => autoBatchEnhancer,
+  buildCreateSlice: () => buildCreateSlice,
+  clearAllListeners: () => clearAllListeners,
+  combineSlices: () => combineSlices,
+  configureStore: () => configureStore,
+  createAction: () => createAction,
+  createActionCreatorInvariantMiddleware: () => createActionCreatorInvariantMiddleware,
+  createAsyncThunk: () => createAsyncThunk,
+  createDraftSafeSelector: () => createDraftSafeSelector,
+  createDraftSafeSelectorCreator: () => createDraftSafeSelectorCreator,
+  createDynamicMiddleware: () => createDynamicMiddleware,
+  createEntityAdapter: () => createEntityAdapter,
+  createImmutableStateInvariantMiddleware: () => createImmutableStateInvariantMiddleware,
+  createListenerMiddleware: () => createListenerMiddleware,
+  createNextState: () => import_immer.produce,
+  createReducer: () => createReducer,
+  createSelector: () => import_reselect2.createSelector,
+  createSelectorCreator: () => import_reselect.createSelectorCreator,
+  createSerializableStateInvariantMiddleware: () => createSerializableStateInvariantMiddleware,
+  createSlice: () => createSlice,
+  current: () => import_immer.current,
+  findNonSerializableValue: () => findNonSerializableValue,
+  formatProdErrorMessage: () => formatProdErrorMessage,
+  freeze: () => import_immer2.freeze,
+  isActionCreator: () => isActionCreator,
+  isAllOf: () => isAllOf,
+  isAnyOf: () => isAnyOf,
+  isAsyncThunkAction: () => isAsyncThunkAction,
+  isDraft: () => import_immer.isDraft,
+  isFluxStandardAction: () => isFSA,
+  isFulfilled: () => isFulfilled,
+  isImmutableDefault: () => isImmutableDefault,
+  isPending: () => isPending,
+  isPlain: () => isPlain,
+  isRejected: () => isRejected,
+  isRejectedWithValue: () => isRejectedWithValue,
+  lruMemoize: () => import_reselect2.lruMemoize,
+  miniSerializeError: () => miniSerializeError,
+  nanoid: () => nanoid,
+  original: () => import_immer2.original,
+  prepareAutoBatched: () => prepareAutoBatched,
+  removeListener: () => removeListener,
+  unwrapResult: () => unwrapResult,
+  weakMapMemoize: () => import_reselect.weakMapMemoize
+});
+module.exports = __toCommonJS(src_exports);
+__reExport(src_exports, require("redux"), module.exports);
+var import_immer2 = require("immer");
+
+// src/immerImports.ts
+var import_immer = require("immer");
+
+// src/index.ts
+var import_reselect2 = require("reselect");
+
+// src/reselectImports.ts
+var import_reselect = require("reselect");
+
+// src/createDraftSafeSelector.ts
+var createDraftSafeSelectorCreator = (...args) => {
+  const createSelector2 = (0, import_reselect.createSelectorCreator)(...args);
+  const createDraftSafeSelector2 = Object.assign((...args2) => {
+    const selector = createSelector2(...args2);
+    const wrappedSelector = (value, ...rest) => selector((0, import_immer.isDraft)(value) ? (0, import_immer.current)(value) : value, ...rest);
+    Object.assign(wrappedSelector, selector);
+    return wrappedSelector;
+  }, {
+    withTypes: () => createDraftSafeSelector2
+  });
+  return createDraftSafeSelector2;
+};
+var createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(import_reselect.weakMapMemoize);
+
+// src/reduxImports.ts
+var import_redux = require("redux");
+
+// src/devtoolsExtension.ts
+var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
+  if (arguments.length === 0) return void 0;
+  if (typeof arguments[0] === "object") return import_redux.compose;
+  return import_redux.compose.apply(null, arguments);
+};
+var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
+  return function(noop3) {
+    return noop3;
+  };
+};
+
+// src/getDefaultMiddleware.ts
+var import_redux_thunk = require("redux-thunk");
+
+// src/tsHelpers.ts
+var hasMatchFunction = (v) => {
+  return v && typeof v.match === "function";
+};
+
+// src/createAction.ts
+function createAction(type, prepareAction) {
+  function actionCreator(...args) {
+    if (prepareAction) {
+      let prepared = prepareAction(...args);
+      if (!prepared) {
+        throw new Error(false ? _formatProdErrorMessage(0) : "prepareAction did not return an object");
+      }
+      return {
+        type,
+        payload: prepared.payload,
+        ..."meta" in prepared && {
+          meta: prepared.meta
+        },
+        ..."error" in prepared && {
+          error: prepared.error
+        }
+      };
+    }
+    return {
+      type,
+      payload: args[0]
+    };
+  }
+  actionCreator.toString = () => `${type}`;
+  actionCreator.type = type;
+  actionCreator.match = (action) => (0, import_redux.isAction)(action) && action.type === type;
+  return actionCreator;
+}
+function isActionCreator(action) {
+  return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
+  hasMatchFunction(action);
+}
+function isFSA(action) {
+  return (0, import_redux.isAction)(action) && Object.keys(action).every(isValidKey);
+}
+function isValidKey(key) {
+  return ["type", "payload", "error", "meta"].indexOf(key) > -1;
+}
+
+// src/actionCreatorInvariantMiddleware.ts
+function getMessage(type) {
+  const splitType = type ? `${type}`.split("/") : [];
+  const actionName = splitType[splitType.length - 1] || "actionCreator";
+  return `Detected an action creator with type "${type || "unknown"}" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`;
+}
+function createActionCreatorInvariantMiddleware(options = {}) {
+  if (false) {
+    return () => (next) => (action) => next(action);
+  }
+  const {
+    isActionCreator: isActionCreator2 = isActionCreator
+  } = options;
+  return () => (next) => (action) => {
+    if (isActionCreator2(action)) {
+      console.warn(getMessage(action.type));
+    }
+    return next(action);
+  };
+}
+
+// src/utils.ts
+function getTimeMeasureUtils(maxDelay, fnName) {
+  let elapsed = 0;
+  return {
+    measureTime(fn) {
+      const started = Date.now();
+      try {
+        return fn();
+      } finally {
+        const finished = Date.now();
+        elapsed += finished - started;
+      }
+    },
+    warnIfExceeded() {
+      if (elapsed > maxDelay) {
+        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. 
+If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
+It is disabled in production builds, so you don't need to worry about that.`);
+      }
+    }
+  };
+}
+var Tuple = class _Tuple extends Array {
+  constructor(...items) {
+    super(...items);
+    Object.setPrototypeOf(this, _Tuple.prototype);
+  }
+  static get [Symbol.species]() {
+    return _Tuple;
+  }
+  concat(...arr) {
+    return super.concat.apply(this, arr);
+  }
+  prepend(...arr) {
+    if (arr.length === 1 && Array.isArray(arr[0])) {
+      return new _Tuple(...arr[0].concat(this));
+    }
+    return new _Tuple(...arr.concat(this));
+  }
+};
+function freezeDraftable(val) {
+  return (0, import_immer.isDraftable)(val) ? (0, import_immer.produce)(val, () => {
+  }) : val;
+}
+function getOrInsertComputed(map, key, compute) {
+  if (map.has(key)) return map.get(key);
+  return map.set(key, compute(key)).get(key);
+}
+
+// src/immutableStateInvariantMiddleware.ts
+function isImmutableDefault(value) {
+  return typeof value !== "object" || value == null || Object.isFrozen(value);
+}
+function trackForMutations(isImmutable, ignoredPaths, obj) {
+  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);
+  return {
+    detectMutations() {
+      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);
+    }
+  };
+}
+function trackProperties(isImmutable, ignoredPaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
+  const tracked = {
+    value: obj
+  };
+  if (!isImmutable(obj) && !checkedObjects.has(obj)) {
+    checkedObjects.add(obj);
+    tracked.children = {};
+    const hasIgnoredPaths = ignoredPaths.length > 0;
+    for (const key in obj) {
+      const nestedPath = path ? path + "." + key : key;
+      if (hasIgnoredPaths) {
+        const hasMatches = ignoredPaths.some((ignored) => {
+          if (ignored instanceof RegExp) {
+            return ignored.test(nestedPath);
+          }
+          return nestedPath === ignored;
+        });
+        if (hasMatches) {
+          continue;
+        }
+      }
+      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);
+    }
+  }
+  return tracked;
+}
+function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
+  const prevObj = trackedProperty ? trackedProperty.value : void 0;
+  const sameRef = prevObj === obj;
+  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
+    return {
+      wasMutated: true,
+      path
+    };
+  }
+  if (isImmutable(prevObj) || isImmutable(obj)) {
+    return {
+      wasMutated: false
+    };
+  }
+  const keysToDetect = {};
+  for (let key in trackedProperty.children) {
+    keysToDetect[key] = true;
+  }
+  for (let key in obj) {
+    keysToDetect[key] = true;
+  }
+  const hasIgnoredPaths = ignoredPaths.length > 0;
+  for (let key in keysToDetect) {
+    const nestedPath = path ? path + "." + key : key;
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath);
+        }
+        return nestedPath === ignored;
+      });
+      if (hasMatches) {
+        continue;
+      }
+    }
+    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
+    if (result.wasMutated) {
+      return result;
+    }
+  }
+  return {
+    wasMutated: false
+  };
+}
+function createImmutableStateInvariantMiddleware(options = {}) {
+  if (false) {
+    return () => (next) => (action) => next(action);
+  } else {
+    let stringify2 = function(obj, serializer, indent, decycler) {
+      return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
+    }, getSerialize2 = function(serializer, decycler) {
+      let stack = [], keys = [];
+      if (!decycler) decycler = function(_, value) {
+        if (stack[0] === value) return "[Circular ~]";
+        return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
+      };
+      return function(key, value) {
+        if (stack.length > 0) {
+          var thisPos = stack.indexOf(this);
+          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
+          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
+          if (~stack.indexOf(value)) value = decycler.call(this, key, value);
+        } else stack.push(value);
+        return serializer == null ? value : serializer.call(this, key, value);
+      };
+    };
+    var stringify = stringify2, getSerialize = getSerialize2;
+    let {
+      isImmutable = isImmutableDefault,
+      ignoredPaths,
+      warnAfter = 32
+    } = options;
+    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
+    return ({
+      getState
+    }) => {
+      let state = getState();
+      let tracker = track(state);
+      let result;
+      return (next) => (action) => {
+        const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
+        measureUtils.measureTime(() => {
+          state = getState();
+          result = tracker.detectMutations();
+          tracker = track(state);
+          if (result.wasMutated) {
+            throw new Error(false ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
+          }
+        });
+        const dispatchedAction = next(action);
+        measureUtils.measureTime(() => {
+          state = getState();
+          result = tracker.detectMutations();
+          tracker = track(state);
+          if (result.wasMutated) {
+            throw new Error(false ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
+          }
+        });
+        measureUtils.warnIfExceeded();
+        return dispatchedAction;
+      };
+    };
+  }
+}
+
+// src/serializableStateInvariantMiddleware.ts
+function isPlain(val) {
+  const type = typeof val;
+  return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || (0, import_redux.isPlainObject)(val);
+}
+function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
+  let foundNestedSerializable;
+  if (!isSerializable(value)) {
+    return {
+      keyPath: path || "<root>",
+      value
+    };
+  }
+  if (typeof value !== "object" || value === null) {
+    return false;
+  }
+  if (cache?.has(value)) return false;
+  const entries = getEntries != null ? getEntries(value) : Object.entries(value);
+  const hasIgnoredPaths = ignoredPaths.length > 0;
+  for (const [key, nestedValue] of entries) {
+    const nestedPath = path ? path + "." + key : key;
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath);
+        }
+        return nestedPath === ignored;
+      });
+      if (hasMatches) {
+        continue;
+      }
+    }
+    if (!isSerializable(nestedValue)) {
+      return {
+        keyPath: nestedPath,
+        value: nestedValue
+      };
+    }
+    if (typeof nestedValue === "object") {
+      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
+      if (foundNestedSerializable) {
+        return foundNestedSerializable;
+      }
+    }
+  }
+  if (cache && isNestedFrozen(value)) cache.add(value);
+  return false;
+}
+function isNestedFrozen(value) {
+  if (!Object.isFrozen(value)) return false;
+  for (const nestedValue of Object.values(value)) {
+    if (typeof nestedValue !== "object" || nestedValue === null) continue;
+    if (!isNestedFrozen(nestedValue)) return false;
+  }
+  return true;
+}
+function createSerializableStateInvariantMiddleware(options = {}) {
+  if (false) {
+    return () => (next) => (action) => next(action);
+  } else {
+    const {
+      isSerializable = isPlain,
+      getEntries,
+      ignoredActions = [],
+      ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
+      ignoredPaths = [],
+      warnAfter = 32,
+      ignoreState = false,
+      ignoreActions = false,
+      disableCache = false
+    } = options;
+    const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
+    return (storeAPI) => (next) => (action) => {
+      if (!(0, import_redux.isAction)(action)) {
+        return next(action);
+      }
+      const result = next(action);
+      const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
+      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
+        measureUtils.measureTime(() => {
+          const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
+          if (foundActionNonSerializableValue) {
+            const {
+              keyPath,
+              value
+            } = foundActionNonSerializableValue;
+            console.error(`A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`, value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
+          }
+        });
+      }
+      if (!ignoreState) {
+        measureUtils.measureTime(() => {
+          const state = storeAPI.getState();
+          const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
+          if (foundStateNonSerializableValue) {
+            const {
+              keyPath,
+              value
+            } = foundStateNonSerializableValue;
+            console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
+Take a look at the reducer(s) handling this action type: ${action.type}.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
+          }
+        });
+        measureUtils.warnIfExceeded();
+      }
+      return result;
+    };
+  }
+}
+
+// src/getDefaultMiddleware.ts
+function isBoolean(x) {
+  return typeof x === "boolean";
+}
+var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
+  const {
+    thunk = true,
+    immutableCheck = true,
+    serializableCheck = true,
+    actionCreatorCheck = true
+  } = options ?? {};
+  let middlewareArray = new Tuple();
+  if (thunk) {
+    if (isBoolean(thunk)) {
+      middlewareArray.push(import_redux_thunk.thunk);
+    } else {
+      middlewareArray.push((0, import_redux_thunk.withExtraArgument)(thunk.extraArgument));
+    }
+  }
+  if (true) {
+    if (immutableCheck) {
+      let immutableOptions = {};
+      if (!isBoolean(immutableCheck)) {
+        immutableOptions = immutableCheck;
+      }
+      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
+    }
+    if (serializableCheck) {
+      let serializableOptions = {};
+      if (!isBoolean(serializableCheck)) {
+        serializableOptions = serializableCheck;
+      }
+      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
+    }
+    if (actionCreatorCheck) {
+      let actionCreatorOptions = {};
+      if (!isBoolean(actionCreatorCheck)) {
+        actionCreatorOptions = actionCreatorCheck;
+      }
+      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
+    }
+  }
+  return middlewareArray;
+};
+
+// src/autoBatchEnhancer.ts
+var SHOULD_AUTOBATCH = "RTK_autoBatch";
+var prepareAutoBatched = () => (payload) => ({
+  payload,
+  meta: {
+    [SHOULD_AUTOBATCH]: true
+  }
+});
+var createQueueWithTimer = (timeout) => {
+  return (notify) => {
+    setTimeout(notify, timeout);
+  };
+};
+var autoBatchEnhancer = (options = {
+  type: "raf"
+}) => (next) => (...args) => {
+  const store = next(...args);
+  let notifying = true;
+  let shouldNotifyAtEndOfTick = false;
+  let notificationQueued = false;
+  const listeners = /* @__PURE__ */ new Set();
+  const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? (
+    // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
+    typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10)
+  ) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
+  const notifyListeners = () => {
+    notificationQueued = false;
+    if (shouldNotifyAtEndOfTick) {
+      shouldNotifyAtEndOfTick = false;
+      listeners.forEach((l) => l());
+    }
+  };
+  return Object.assign({}, store, {
+    // Override the base `store.subscribe` method to keep original listeners
+    // from running if we're delaying notifications
+    subscribe(listener2) {
+      const wrappedListener = () => notifying && listener2();
+      const unsubscribe = store.subscribe(wrappedListener);
+      listeners.add(listener2);
+      return () => {
+        unsubscribe();
+        listeners.delete(listener2);
+      };
+    },
+    // Override the base `store.dispatch` method so that we can check actions
+    // for the `shouldAutoBatch` flag and determine if batching is active
+    dispatch(action) {
+      try {
+        notifying = !action?.meta?.[SHOULD_AUTOBATCH];
+        shouldNotifyAtEndOfTick = !notifying;
+        if (shouldNotifyAtEndOfTick) {
+          if (!notificationQueued) {
+            notificationQueued = true;
+            queueCallback(notifyListeners);
+          }
+        }
+        return store.dispatch(action);
+      } finally {
+        notifying = true;
+      }
+    }
+  });
+};
+
+// src/getDefaultEnhancers.ts
+var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
+  const {
+    autoBatch = true
+  } = options ?? {};
+  let enhancerArray = new Tuple(middlewareEnhancer);
+  if (autoBatch) {
+    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
+  }
+  return enhancerArray;
+};
+
+// src/configureStore.ts
+function configureStore(options) {
+  const getDefaultMiddleware = buildGetDefaultMiddleware();
+  const {
+    reducer = void 0,
+    middleware,
+    devTools = true,
+    duplicateMiddlewareCheck = true,
+    preloadedState = void 0,
+    enhancers = void 0
+  } = options || {};
+  let rootReducer;
+  if (typeof reducer === "function") {
+    rootReducer = reducer;
+  } else if ((0, import_redux.isPlainObject)(reducer)) {
+    rootReducer = (0, import_redux.combineReducers)(reducer);
+  } else {
+    throw new Error(false ? _formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
+  }
+  if (middleware && typeof middleware !== "function") {
+    throw new Error(false ? _formatProdErrorMessage2(2) : "`middleware` field must be a callback");
+  }
+  let finalMiddleware;
+  if (typeof middleware === "function") {
+    finalMiddleware = middleware(getDefaultMiddleware);
+    if (!Array.isArray(finalMiddleware)) {
+      throw new Error(false ? _formatProdErrorMessage3(3) : "when using a middleware builder function, an array of middleware must be returned");
+    }
+  } else {
+    finalMiddleware = getDefaultMiddleware();
+  }
+  if (finalMiddleware.some((item) => typeof item !== "function")) {
+    throw new Error(false ? _formatProdErrorMessage4(4) : "each middleware provided to configureStore must be a function");
+  }
+  if (duplicateMiddlewareCheck) {
+    let middlewareReferences = /* @__PURE__ */ new Set();
+    finalMiddleware.forEach((middleware2) => {
+      if (middlewareReferences.has(middleware2)) {
+        throw new Error(false ? _formatProdErrorMessage5(42) : "Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");
+      }
+      middlewareReferences.add(middleware2);
+    });
+  }
+  let finalCompose = import_redux.compose;
+  if (devTools) {
+    finalCompose = composeWithDevTools({
+      // Enable capture of stack traces for dispatched Redux actions
+      trace: true,
+      ...typeof devTools === "object" && devTools
+    });
+  }
+  const middlewareEnhancer = (0, import_redux.applyMiddleware)(...finalMiddleware);
+  const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
+  if (enhancers && typeof enhancers !== "function") {
+    throw new Error(false ? _formatProdErrorMessage6(5) : "`enhancers` field must be a callback");
+  }
+  let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
+  if (!Array.isArray(storeEnhancers)) {
+    throw new Error(false ? _formatProdErrorMessage7(6) : "`enhancers` callback must return an array");
+  }
+  if (storeEnhancers.some((item) => typeof item !== "function")) {
+    throw new Error(false ? _formatProdErrorMessage8(7) : "each enhancer provided to configureStore must be a function");
+  }
+  if (finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
+    console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
+  }
+  const composedEnhancer = finalCompose(...storeEnhancers);
+  return (0, import_redux.createStore)(rootReducer, preloadedState, composedEnhancer);
+}
+
+// src/mapBuilders.ts
+function executeReducerBuilderCallback(builderCallback) {
+  const actionsMap = {};
+  const actionMatchers = [];
+  let defaultCaseReducer;
+  const builder = {
+    addCase(typeOrActionCreator, reducer) {
+      if (true) {
+        if (actionMatchers.length > 0) {
+          throw new Error(false ? _formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
+        }
+        if (defaultCaseReducer) {
+          throw new Error(false ? _formatProdErrorMessage2(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
+      if (!type) {
+        throw new Error(false ? _formatProdErrorMessage3(28) : "`builder.addCase` cannot be called with an empty action type");
+      }
+      if (type in actionsMap) {
+        throw new Error(false ? _formatProdErrorMessage4(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
+      }
+      actionsMap[type] = reducer;
+      return builder;
+    },
+    addAsyncThunk(asyncThunk, reducers) {
+      if (true) {
+        if (defaultCaseReducer) {
+          throw new Error(false ? _formatProdErrorMessage5(43) : "`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
+      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
+      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
+      if (reducers.settled) actionMatchers.push({
+        matcher: asyncThunk.settled,
+        reducer: reducers.settled
+      });
+      return builder;
+    },
+    addMatcher(matcher, reducer) {
+      if (true) {
+        if (defaultCaseReducer) {
+          throw new Error(false ? _formatProdErrorMessage6(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      actionMatchers.push({
+        matcher,
+        reducer
+      });
+      return builder;
+    },
+    addDefaultCase(reducer) {
+      if (true) {
+        if (defaultCaseReducer) {
+          throw new Error(false ? _formatProdErrorMessage7(31) : "`builder.addDefaultCase` can only be called once");
+        }
+      }
+      defaultCaseReducer = reducer;
+      return builder;
+    }
+  };
+  builderCallback(builder);
+  return [actionsMap, actionMatchers, defaultCaseReducer];
+}
+
+// src/createReducer.ts
+function isStateFunction(x) {
+  return typeof x === "function";
+}
+function createReducer(initialState, mapOrBuilderCallback) {
+  if (true) {
+    if (typeof mapOrBuilderCallback === "object") {
+      throw new Error(false ? _formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
+    }
+  }
+  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
+  let getInitialState;
+  if (isStateFunction(initialState)) {
+    getInitialState = () => freezeDraftable(initialState());
+  } else {
+    const frozenInitialState = freezeDraftable(initialState);
+    getInitialState = () => frozenInitialState;
+  }
+  function reducer(state = getInitialState(), action) {
+    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
+      matcher
+    }) => matcher(action)).map(({
+      reducer: reducer2
+    }) => reducer2)];
+    if (caseReducers.filter((cr) => !!cr).length === 0) {
+      caseReducers = [finalDefaultCaseReducer];
+    }
+    return caseReducers.reduce((previousState, caseReducer) => {
+      if (caseReducer) {
+        if ((0, import_immer.isDraft)(previousState)) {
+          const draft = previousState;
+          const result = caseReducer(draft, action);
+          if (result === void 0) {
+            return previousState;
+          }
+          return result;
+        } else if (!(0, import_immer.isDraftable)(previousState)) {
+          const result = caseReducer(previousState, action);
+          if (result === void 0) {
+            if (previousState === null) {
+              return previousState;
+            }
+            throw Error("A case reducer on a non-draftable value must not return undefined");
+          }
+          return result;
+        } else {
+          return (0, import_immer.produce)(previousState, (draft) => {
+            return caseReducer(draft, action);
+          });
+        }
+      }
+      return previousState;
+    }, state);
+  }
+  reducer.getInitialState = getInitialState;
+  return reducer;
+}
+
+// src/matchers.ts
+var matches = (matcher, action) => {
+  if (hasMatchFunction(matcher)) {
+    return matcher.match(action);
+  } else {
+    return matcher(action);
+  }
+};
+function isAnyOf(...matchers) {
+  return (action) => {
+    return matchers.some((matcher) => matches(matcher, action));
+  };
+}
+function isAllOf(...matchers) {
+  return (action) => {
+    return matchers.every((matcher) => matches(matcher, action));
+  };
+}
+function hasExpectedRequestMetadata(action, validStatus) {
+  if (!action || !action.meta) return false;
+  const hasValidRequestId = typeof action.meta.requestId === "string";
+  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
+  return hasValidRequestId && hasValidRequestStatus;
+}
+function isAsyncThunkArray(a) {
+  return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
+}
+function isPending(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["pending"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isPending()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
+}
+function isRejected(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejected()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
+}
+function isRejectedWithValue(...asyncThunks) {
+  const hasFlag = (action) => {
+    return action && action.meta && action.meta.rejectedWithValue;
+  };
+  if (asyncThunks.length === 0) {
+    return isAllOf(isRejected(...asyncThunks), hasFlag);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejectedWithValue()(asyncThunks[0]);
+  }
+  return isAllOf(isRejected(...asyncThunks), hasFlag);
+}
+function isFulfilled(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isFulfilled()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
+}
+function isAsyncThunkAction(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isAsyncThunkAction()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));
+}
+
+// src/nanoid.ts
+var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
+var nanoid = (size = 21) => {
+  let id = "";
+  let i = size;
+  while (i--) {
+    id += urlAlphabet[Math.random() * 64 | 0];
+  }
+  return id;
+};
+
+// src/createAsyncThunk.ts
+var commonProperties = ["name", "message", "stack", "code"];
+var RejectWithValue = class {
+  constructor(payload, meta) {
+    this.payload = payload;
+    this.meta = meta;
+  }
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  _type;
+};
+var FulfillWithMeta = class {
+  constructor(payload, meta) {
+    this.payload = payload;
+    this.meta = meta;
+  }
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  _type;
+};
+var miniSerializeError = (value) => {
+  if (typeof value === "object" && value !== null) {
+    const simpleError = {};
+    for (const property of commonProperties) {
+      if (typeof value[property] === "string") {
+        simpleError[property] = value[property];
+      }
+    }
+    return simpleError;
+  }
+  return {
+    message: String(value)
+  };
+};
+var externalAbortMessage = "External signal was aborted";
+var createAsyncThunk = /* @__PURE__ */ (() => {
+  function createAsyncThunk2(typePrefix, payloadCreator, options) {
+    const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
+      payload,
+      meta: {
+        ...meta || {},
+        arg,
+        requestId,
+        requestStatus: "fulfilled"
+      }
+    }));
+    const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
+      payload: void 0,
+      meta: {
+        ...meta || {},
+        arg,
+        requestId,
+        requestStatus: "pending"
+      }
+    }));
+    const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
+      payload,
+      error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
+      meta: {
+        ...meta || {},
+        arg,
+        requestId,
+        rejectedWithValue: !!payload,
+        requestStatus: "rejected",
+        aborted: error?.name === "AbortError",
+        condition: error?.name === "ConditionError"
+      }
+    }));
+    function actionCreator(arg, {
+      signal
+    } = {}) {
+      return (dispatch, getState, extra) => {
+        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();
+        const abortController = new AbortController();
+        let abortHandler;
+        let abortReason;
+        function abort(reason) {
+          abortReason = reason;
+          abortController.abort();
+        }
+        if (signal) {
+          if (signal.aborted) {
+            abort(externalAbortMessage);
+          } else {
+            signal.addEventListener("abort", () => abort(externalAbortMessage), {
+              once: true
+            });
+          }
+        }
+        const promise = async function() {
+          let finalAction;
+          try {
+            let conditionResult = options?.condition?.(arg, {
+              getState,
+              extra
+            });
+            if (isThenable(conditionResult)) {
+              conditionResult = await conditionResult;
+            }
+            if (conditionResult === false || abortController.signal.aborted) {
+              throw {
+                name: "ConditionError",
+                message: "Aborted due to condition callback returning false."
+              };
+            }
+            const abortedPromise = new Promise((_, reject) => {
+              abortHandler = () => {
+                reject({
+                  name: "AbortError",
+                  message: abortReason || "Aborted"
+                });
+              };
+              abortController.signal.addEventListener("abort", abortHandler, {
+                once: true
+              });
+            });
+            dispatch(pending(requestId, arg, options?.getPendingMeta?.({
+              requestId,
+              arg
+            }, {
+              getState,
+              extra
+            })));
+            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
+              dispatch,
+              getState,
+              extra,
+              requestId,
+              signal: abortController.signal,
+              abort,
+              rejectWithValue: (value, meta) => {
+                return new RejectWithValue(value, meta);
+              },
+              fulfillWithValue: (value, meta) => {
+                return new FulfillWithMeta(value, meta);
+              }
+            })).then((result) => {
+              if (result instanceof RejectWithValue) {
+                throw result;
+              }
+              if (result instanceof FulfillWithMeta) {
+                return fulfilled(result.payload, requestId, arg, result.meta);
+              }
+              return fulfilled(result, requestId, arg);
+            })]);
+          } catch (err) {
+            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
+          } finally {
+            if (abortHandler) {
+              abortController.signal.removeEventListener("abort", abortHandler);
+            }
+          }
+          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
+          if (!skipDispatch) {
+            dispatch(finalAction);
+          }
+          return finalAction;
+        }();
+        return Object.assign(promise, {
+          abort,
+          requestId,
+          arg,
+          unwrap() {
+            return promise.then(unwrapResult);
+          }
+        });
+      };
+    }
+    return Object.assign(actionCreator, {
+      pending,
+      rejected,
+      fulfilled,
+      settled: isAnyOf(rejected, fulfilled),
+      typePrefix
+    });
+  }
+  createAsyncThunk2.withTypes = () => createAsyncThunk2;
+  return createAsyncThunk2;
+})();
+function unwrapResult(action) {
+  if (action.meta && action.meta.rejectedWithValue) {
+    throw action.payload;
+  }
+  if (action.error) {
+    throw action.error;
+  }
+  return action.payload;
+}
+function isThenable(value) {
+  return value !== null && typeof value === "object" && typeof value.then === "function";
+}
+
+// src/createSlice.ts
+var asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
+var asyncThunkCreator = {
+  [asyncThunkSymbol]: createAsyncThunk
+};
+var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
+  ReducerType2["reducer"] = "reducer";
+  ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
+  ReducerType2["asyncThunk"] = "asyncThunk";
+  return ReducerType2;
+})(ReducerType || {});
+function getType(slice, actionKey) {
+  return `${slice}/${actionKey}`;
+}
+function buildCreateSlice({
+  creators
+} = {}) {
+  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];
+  return function createSlice2(options) {
+    const {
+      name,
+      reducerPath = name
+    } = options;
+    if (!name) {
+      throw new Error(false ? _formatProdErrorMessage(11) : "`name` is a required option for createSlice");
+    }
+    if (typeof process !== "undefined" && true) {
+      if (options.initialState === void 0) {
+        console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
+      }
+    }
+    const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
+    const reducerNames = Object.keys(reducers);
+    const context = {
+      sliceCaseReducersByName: {},
+      sliceCaseReducersByType: {},
+      actionCreators: {},
+      sliceMatchers: []
+    };
+    const contextMethods = {
+      addCase(typeOrActionCreator, reducer2) {
+        const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
+        if (!type) {
+          throw new Error(false ? _formatProdErrorMessage2(12) : "`context.addCase` cannot be called with an empty action type");
+        }
+        if (type in context.sliceCaseReducersByType) {
+          throw new Error(false ? _formatProdErrorMessage3(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
+        }
+        context.sliceCaseReducersByType[type] = reducer2;
+        return contextMethods;
+      },
+      addMatcher(matcher, reducer2) {
+        context.sliceMatchers.push({
+          matcher,
+          reducer: reducer2
+        });
+        return contextMethods;
+      },
+      exposeAction(name2, actionCreator) {
+        context.actionCreators[name2] = actionCreator;
+        return contextMethods;
+      },
+      exposeCaseReducer(name2, reducer2) {
+        context.sliceCaseReducersByName[name2] = reducer2;
+        return contextMethods;
+      }
+    };
+    reducerNames.forEach((reducerName) => {
+      const reducerDefinition = reducers[reducerName];
+      const reducerDetails = {
+        reducerName,
+        type: getType(name, reducerName),
+        createNotation: typeof options.reducers === "function"
+      };
+      if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
+        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
+      } else {
+        handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
+      }
+    });
+    function buildReducer() {
+      if (true) {
+        if (typeof options.extraReducers === "object") {
+          throw new Error(false ? _formatProdErrorMessage4(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
+        }
+      }
+      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
+      const finalCaseReducers = {
+        ...extraReducers,
+        ...context.sliceCaseReducersByType
+      };
+      return createReducer(options.initialState, (builder) => {
+        for (let key in finalCaseReducers) {
+          builder.addCase(key, finalCaseReducers[key]);
+        }
+        for (let sM of context.sliceMatchers) {
+          builder.addMatcher(sM.matcher, sM.reducer);
+        }
+        for (let m of actionMatchers) {
+          builder.addMatcher(m.matcher, m.reducer);
+        }
+        if (defaultCaseReducer) {
+          builder.addDefaultCase(defaultCaseReducer);
+        }
+      });
+    }
+    const selectSelf = (state) => state;
+    const injectedSelectorCache = /* @__PURE__ */ new Map();
+    const injectedStateCache = /* @__PURE__ */ new WeakMap();
+    let _reducer;
+    function reducer(state, action) {
+      if (!_reducer) _reducer = buildReducer();
+      return _reducer(state, action);
+    }
+    function getInitialState() {
+      if (!_reducer) _reducer = buildReducer();
+      return _reducer.getInitialState();
+    }
+    function makeSelectorProps(reducerPath2, injected = false) {
+      function selectSlice(state) {
+        let sliceState = state[reducerPath2];
+        if (typeof sliceState === "undefined") {
+          if (injected) {
+            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);
+          } else if (true) {
+            throw new Error(false ? _formatProdErrorMessage5(15) : "selectSlice returned undefined for an uninjected slice reducer");
+          }
+        }
+        return sliceState;
+      }
+      function getSelectors(selectState = selectSelf) {
+        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => /* @__PURE__ */ new WeakMap());
+        return getOrInsertComputed(selectorCache, selectState, () => {
+          const map = {};
+          for (const [name2, selector] of Object.entries(options.selectors ?? {})) {
+            map[name2] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);
+          }
+          return map;
+        });
+      }
+      return {
+        reducerPath: reducerPath2,
+        getSelectors,
+        get selectors() {
+          return getSelectors(selectSlice);
+        },
+        selectSlice
+      };
+    }
+    const slice = {
+      name,
+      reducer,
+      actions: context.actionCreators,
+      caseReducers: context.sliceCaseReducersByName,
+      getInitialState,
+      ...makeSelectorProps(reducerPath),
+      injectInto(injectable, {
+        reducerPath: pathOpt,
+        ...config
+      } = {}) {
+        const newReducerPath = pathOpt ?? reducerPath;
+        injectable.inject({
+          reducerPath: newReducerPath,
+          reducer
+        }, config);
+        return {
+          ...slice,
+          ...makeSelectorProps(newReducerPath, true)
+        };
+      }
+    };
+    return slice;
+  };
+}
+function wrapSelector(selector, selectState, getInitialState, injected) {
+  function wrapper(rootState, ...args) {
+    let sliceState = selectState(rootState);
+    if (typeof sliceState === "undefined") {
+      if (injected) {
+        sliceState = getInitialState();
+      } else if (true) {
+        throw new Error(false ? _formatProdErrorMessage6(16) : "selectState returned undefined for an uninjected slice reducer");
+      }
+    }
+    return selector(sliceState, ...args);
+  }
+  wrapper.unwrapped = selector;
+  return wrapper;
+}
+var createSlice = /* @__PURE__ */ buildCreateSlice();
+function buildReducerCreators() {
+  function asyncThunk(payloadCreator, config) {
+    return {
+      _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
+      payloadCreator,
+      ...config
+    };
+  }
+  asyncThunk.withTypes = () => asyncThunk;
+  return {
+    reducer(caseReducer) {
+      return Object.assign({
+        // hack so the wrapping function has the same name as the original
+        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
+        [caseReducer.name](...args) {
+          return caseReducer(...args);
+        }
+      }[caseReducer.name], {
+        _reducerDefinitionType: "reducer" /* reducer */
+      });
+    },
+    preparedReducer(prepare, reducer) {
+      return {
+        _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
+        prepare,
+        reducer
+      };
+    },
+    asyncThunk
+  };
+}
+function handleNormalReducerDefinition({
+  type,
+  reducerName,
+  createNotation
+}, maybeReducerWithPrepare, context) {
+  let caseReducer;
+  let prepareCallback;
+  if ("reducer" in maybeReducerWithPrepare) {
+    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
+      throw new Error(false ? _formatProdErrorMessage7(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
+    }
+    caseReducer = maybeReducerWithPrepare.reducer;
+    prepareCallback = maybeReducerWithPrepare.prepare;
+  } else {
+    caseReducer = maybeReducerWithPrepare;
+  }
+  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
+}
+function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
+  return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
+}
+function isCaseReducerWithPrepareDefinition(reducerDefinition) {
+  return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
+}
+function handleThunkCaseReducerDefinition({
+  type,
+  reducerName
+}, reducerDefinition, context, cAT) {
+  if (!cAT) {
+    throw new Error(false ? _formatProdErrorMessage8(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
+  }
+  const {
+    payloadCreator,
+    fulfilled,
+    pending,
+    rejected,
+    settled,
+    options
+  } = reducerDefinition;
+  const thunk = cAT(type, payloadCreator, options);
+  context.exposeAction(reducerName, thunk);
+  if (fulfilled) {
+    context.addCase(thunk.fulfilled, fulfilled);
+  }
+  if (pending) {
+    context.addCase(thunk.pending, pending);
+  }
+  if (rejected) {
+    context.addCase(thunk.rejected, rejected);
+  }
+  if (settled) {
+    context.addMatcher(thunk.settled, settled);
+  }
+  context.exposeCaseReducer(reducerName, {
+    fulfilled: fulfilled || noop,
+    pending: pending || noop,
+    rejected: rejected || noop,
+    settled: settled || noop
+  });
+}
+function noop() {
+}
+
+// src/entities/entity_state.ts
+function getInitialEntityState() {
+  return {
+    ids: [],
+    entities: {}
+  };
+}
+function createInitialStateFactory(stateAdapter) {
+  function getInitialState(additionalState = {}, entities) {
+    const state = Object.assign(getInitialEntityState(), additionalState);
+    return entities ? stateAdapter.setAll(state, entities) : state;
+  }
+  return {
+    getInitialState
+  };
+}
+
+// src/entities/state_selectors.ts
+function createSelectorsFactory() {
+  function getSelectors(selectState, options = {}) {
+    const {
+      createSelector: createSelector2 = createDraftSafeSelector
+    } = options;
+    const selectIds = (state) => state.ids;
+    const selectEntities = (state) => state.entities;
+    const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
+    const selectId = (_, id) => id;
+    const selectById = (entities, id) => entities[id];
+    const selectTotal = createSelector2(selectIds, (ids) => ids.length);
+    if (!selectState) {
+      return {
+        selectIds,
+        selectEntities,
+        selectAll,
+        selectTotal,
+        selectById: createSelector2(selectEntities, selectId, selectById)
+      };
+    }
+    const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
+    return {
+      selectIds: createSelector2(selectState, selectIds),
+      selectEntities: selectGlobalizedEntities,
+      selectAll: createSelector2(selectState, selectAll),
+      selectTotal: createSelector2(selectState, selectTotal),
+      selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
+    };
+  }
+  return {
+    getSelectors
+  };
+}
+
+// src/entities/state_adapter.ts
+var isDraftTyped = import_immer.isDraft;
+function createSingleArgumentStateOperator(mutator) {
+  const operator = createStateOperator((_, state) => mutator(state));
+  return function operation(state) {
+    return operator(state, void 0);
+  };
+}
+function createStateOperator(mutator) {
+  return function operation(state, arg) {
+    function isPayloadActionArgument(arg2) {
+      return isFSA(arg2);
+    }
+    const runMutator = (draft) => {
+      if (isPayloadActionArgument(arg)) {
+        mutator(arg.payload, draft);
+      } else {
+        mutator(arg, draft);
+      }
+    };
+    if (isDraftTyped(state)) {
+      runMutator(state);
+      return state;
+    }
+    return (0, import_immer.produce)(state, runMutator);
+  };
+}
+
+// src/entities/utils.ts
+function selectIdValue(entity, selectId) {
+  const key = selectId(entity);
+  if (key === void 0) {
+    console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
+  }
+  return key;
+}
+function ensureEntitiesArray(entities) {
+  if (!Array.isArray(entities)) {
+    entities = Object.values(entities);
+  }
+  return entities;
+}
+function getCurrent(value) {
+  return (0, import_immer.isDraft)(value) ? (0, import_immer.current)(value) : value;
+}
+function splitAddedUpdatedEntities(newEntities, selectId, state) {
+  newEntities = ensureEntitiesArray(newEntities);
+  const existingIdsArray = getCurrent(state.ids);
+  const existingIds = new Set(existingIdsArray);
+  const added = [];
+  const addedIds = /* @__PURE__ */ new Set([]);
+  const updated = [];
+  for (const entity of newEntities) {
+    const id = selectIdValue(entity, selectId);
+    if (existingIds.has(id) || addedIds.has(id)) {
+      updated.push({
+        id,
+        changes: entity
+      });
+    } else {
+      addedIds.add(id);
+      added.push(entity);
+    }
+  }
+  return [added, updated, existingIdsArray];
+}
+
+// src/entities/unsorted_state_adapter.ts
+function createUnsortedStateAdapter(selectId) {
+  function addOneMutably(entity, state) {
+    const key = selectIdValue(entity, selectId);
+    if (key in state.entities) {
+      return;
+    }
+    state.ids.push(key);
+    state.entities[key] = entity;
+  }
+  function addManyMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    for (const entity of newEntities) {
+      addOneMutably(entity, state);
+    }
+  }
+  function setOneMutably(entity, state) {
+    const key = selectIdValue(entity, selectId);
+    if (!(key in state.entities)) {
+      state.ids.push(key);
+    }
+    ;
+    state.entities[key] = entity;
+  }
+  function setManyMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    for (const entity of newEntities) {
+      setOneMutably(entity, state);
+    }
+  }
+  function setAllMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    state.ids = [];
+    state.entities = {};
+    addManyMutably(newEntities, state);
+  }
+  function removeOneMutably(key, state) {
+    return removeManyMutably([key], state);
+  }
+  function removeManyMutably(keys, state) {
+    let didMutate = false;
+    keys.forEach((key) => {
+      if (key in state.entities) {
+        delete state.entities[key];
+        didMutate = true;
+      }
+    });
+    if (didMutate) {
+      state.ids = state.ids.filter((id) => id in state.entities);
+    }
+  }
+  function removeAllMutably(state) {
+    Object.assign(state, {
+      ids: [],
+      entities: {}
+    });
+  }
+  function takeNewKey(keys, update, state) {
+    const original3 = state.entities[update.id];
+    if (original3 === void 0) {
+      return false;
+    }
+    const updated = Object.assign({}, original3, update.changes);
+    const newKey = selectIdValue(updated, selectId);
+    const hasNewKey = newKey !== update.id;
+    if (hasNewKey) {
+      keys[update.id] = newKey;
+      delete state.entities[update.id];
+    }
+    ;
+    state.entities[newKey] = updated;
+    return hasNewKey;
+  }
+  function updateOneMutably(update, state) {
+    return updateManyMutably([update], state);
+  }
+  function updateManyMutably(updates, state) {
+    const newKeys = {};
+    const updatesPerEntity = {};
+    updates.forEach((update) => {
+      if (update.id in state.entities) {
+        updatesPerEntity[update.id] = {
+          id: update.id,
+          // Spreads ignore falsy values, so this works even if there isn't
+          // an existing update already at this key
+          changes: {
+            ...updatesPerEntity[update.id]?.changes,
+            ...update.changes
+          }
+        };
+      }
+    });
+    updates = Object.values(updatesPerEntity);
+    const didMutateEntities = updates.length > 0;
+    if (didMutateEntities) {
+      const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
+      if (didMutateIds) {
+        state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
+      }
+    }
+  }
+  function upsertOneMutably(entity, state) {
+    return upsertManyMutably([entity], state);
+  }
+  function upsertManyMutably(newEntities, state) {
+    const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
+    addManyMutably(added, state);
+    updateManyMutably(updated, state);
+  }
+  return {
+    removeAll: createSingleArgumentStateOperator(removeAllMutably),
+    addOne: createStateOperator(addOneMutably),
+    addMany: createStateOperator(addManyMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+    removeOne: createStateOperator(removeOneMutably),
+    removeMany: createStateOperator(removeManyMutably)
+  };
+}
+
+// src/entities/sorted_state_adapter.ts
+function findInsertIndex(sortedItems, item, comparisonFunction) {
+  let lowIndex = 0;
+  let highIndex = sortedItems.length;
+  while (lowIndex < highIndex) {
+    let middleIndex = lowIndex + highIndex >>> 1;
+    const currentItem = sortedItems[middleIndex];
+    const res = comparisonFunction(item, currentItem);
+    if (res >= 0) {
+      lowIndex = middleIndex + 1;
+    } else {
+      highIndex = middleIndex;
+    }
+  }
+  return lowIndex;
+}
+function insert(sortedItems, item, comparisonFunction) {
+  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
+  sortedItems.splice(insertAtIndex, 0, item);
+  return sortedItems;
+}
+function createSortedStateAdapter(selectId, comparer) {
+  const {
+    removeOne,
+    removeMany,
+    removeAll
+  } = createUnsortedStateAdapter(selectId);
+  function addOneMutably(entity, state) {
+    return addManyMutably([entity], state);
+  }
+  function addManyMutably(newEntities, state, existingIds) {
+    newEntities = ensureEntitiesArray(newEntities);
+    const existingKeys = new Set(existingIds ?? getCurrent(state.ids));
+    const addedKeys = /* @__PURE__ */ new Set();
+    const models = newEntities.filter((model) => {
+      const modelId = selectIdValue(model, selectId);
+      const notAdded = !addedKeys.has(modelId);
+      if (notAdded) addedKeys.add(modelId);
+      return !existingKeys.has(modelId) && notAdded;
+    });
+    if (models.length !== 0) {
+      mergeFunction(state, models);
+    }
+  }
+  function setOneMutably(entity, state) {
+    return setManyMutably([entity], state);
+  }
+  function setManyMutably(newEntities, state) {
+    let deduplicatedEntities = {};
+    newEntities = ensureEntitiesArray(newEntities);
+    if (newEntities.length !== 0) {
+      for (const item of newEntities) {
+        const entityId = selectId(item);
+        deduplicatedEntities[entityId] = item;
+        delete state.entities[entityId];
+      }
+      newEntities = ensureEntitiesArray(deduplicatedEntities);
+      mergeFunction(state, newEntities);
+    }
+  }
+  function setAllMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    state.entities = {};
+    state.ids = [];
+    addManyMutably(newEntities, state, []);
+  }
+  function updateOneMutably(update, state) {
+    return updateManyMutably([update], state);
+  }
+  function updateManyMutably(updates, state) {
+    let appliedUpdates = false;
+    let replacedIds = false;
+    for (let update of updates) {
+      const entity = state.entities[update.id];
+      if (!entity) {
+        continue;
+      }
+      appliedUpdates = true;
+      Object.assign(entity, update.changes);
+      const newId = selectId(entity);
+      if (update.id !== newId) {
+        replacedIds = true;
+        delete state.entities[update.id];
+        const oldIndex = state.ids.indexOf(update.id);
+        state.ids[oldIndex] = newId;
+        state.entities[newId] = entity;
+      }
+    }
+    if (appliedUpdates) {
+      mergeFunction(state, [], appliedUpdates, replacedIds);
+    }
+  }
+  function upsertOneMutably(entity, state) {
+    return upsertManyMutably([entity], state);
+  }
+  function upsertManyMutably(newEntities, state) {
+    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
+    if (added.length) {
+      addManyMutably(added, state, existingIdsArray);
+    }
+    if (updated.length) {
+      updateManyMutably(updated, state);
+    }
+  }
+  function areArraysEqual(a, b) {
+    if (a.length !== b.length) {
+      return false;
+    }
+    for (let i = 0; i < a.length; i++) {
+      if (a[i] === b[i]) {
+        continue;
+      }
+      return false;
+    }
+    return true;
+  }
+  const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {
+    const currentEntities = getCurrent(state.entities);
+    const currentIds = getCurrent(state.ids);
+    const stateEntities = state.entities;
+    let ids = currentIds;
+    if (replacedIds) {
+      ids = new Set(currentIds);
+    }
+    let sortedEntities = [];
+    for (const id of ids) {
+      const entity = currentEntities[id];
+      if (entity) {
+        sortedEntities.push(entity);
+      }
+    }
+    const wasPreviouslyEmpty = sortedEntities.length === 0;
+    for (const item of addedItems) {
+      stateEntities[selectId(item)] = item;
+      if (!wasPreviouslyEmpty) {
+        insert(sortedEntities, item, comparer);
+      }
+    }
+    if (wasPreviouslyEmpty) {
+      sortedEntities = addedItems.slice().sort(comparer);
+    } else if (appliedUpdates) {
+      sortedEntities.sort(comparer);
+    }
+    const newSortedIds = sortedEntities.map(selectId);
+    if (!areArraysEqual(currentIds, newSortedIds)) {
+      state.ids = newSortedIds;
+    }
+  };
+  return {
+    removeOne,
+    removeMany,
+    removeAll,
+    addOne: createStateOperator(addOneMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    addMany: createStateOperator(addManyMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertMany: createStateOperator(upsertManyMutably)
+  };
+}
+
+// src/entities/create_adapter.ts
+function createEntityAdapter(options = {}) {
+  const {
+    selectId,
+    sortComparer
+  } = {
+    sortComparer: false,
+    selectId: (instance) => instance.id,
+    ...options
+  };
+  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
+  const stateFactory = createInitialStateFactory(stateAdapter);
+  const selectorsFactory = createSelectorsFactory();
+  return {
+    selectId,
+    sortComparer,
+    ...stateFactory,
+    ...selectorsFactory,
+    ...stateAdapter
+  };
+}
+
+// src/listenerMiddleware/exceptions.ts
+var task = "task";
+var listener = "listener";
+var completed = "completed";
+var cancelled = "cancelled";
+var taskCancelled = `task-${cancelled}`;
+var taskCompleted = `task-${completed}`;
+var listenerCancelled = `${listener}-${cancelled}`;
+var listenerCompleted = `${listener}-${completed}`;
+var TaskAbortError = class {
+  constructor(code) {
+    this.code = code;
+    this.message = `${task} ${cancelled} (reason: ${code})`;
+  }
+  name = "TaskAbortError";
+  message;
+};
+
+// src/listenerMiddleware/utils.ts
+var assertFunction = (func, expected) => {
+  if (typeof func !== "function") {
+    throw new TypeError(false ? _formatProdErrorMessage(32) : `${expected} is not a function`);
+  }
+};
+var noop2 = () => {
+};
+var catchRejection = (promise, onError = noop2) => {
+  promise.catch(onError);
+  return promise;
+};
+var addAbortSignalListener = (abortSignal, callback) => {
+  abortSignal.addEventListener("abort", callback, {
+    once: true
+  });
+  return () => abortSignal.removeEventListener("abort", callback);
+};
+
+// src/listenerMiddleware/task.ts
+var validateActive = (signal) => {
+  if (signal.aborted) {
+    throw new TaskAbortError(signal.reason);
+  }
+};
+function raceWithSignal(signal, promise) {
+  let cleanup = noop2;
+  return new Promise((resolve, reject) => {
+    const notifyRejection = () => reject(new TaskAbortError(signal.reason));
+    if (signal.aborted) {
+      notifyRejection();
+      return;
+    }
+    cleanup = addAbortSignalListener(signal, notifyRejection);
+    promise.finally(() => cleanup()).then(resolve, reject);
+  }).finally(() => {
+    cleanup = noop2;
+  });
+}
+var runTask = async (task2, cleanUp) => {
+  try {
+    await Promise.resolve();
+    const value = await task2();
+    return {
+      status: "ok",
+      value
+    };
+  } catch (error) {
+    return {
+      status: error instanceof TaskAbortError ? "cancelled" : "rejected",
+      error
+    };
+  } finally {
+    cleanUp?.();
+  }
+};
+var createPause = (signal) => {
+  return (promise) => {
+    return catchRejection(raceWithSignal(signal, promise).then((output) => {
+      validateActive(signal);
+      return output;
+    }));
+  };
+};
+var createDelay = (signal) => {
+  const pause = createPause(signal);
+  return (timeoutMs) => {
+    return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
+  };
+};
+
+// src/listenerMiddleware/index.ts
+var {
+  assign
+} = Object;
+var INTERNAL_NIL_TOKEN = {};
+var alm = "listenerMiddleware";
+var createFork = (parentAbortSignal, parentBlockingPromises) => {
+  const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));
+  return (taskExecutor, opts) => {
+    assertFunction(taskExecutor, "taskExecutor");
+    const childAbortController = new AbortController();
+    linkControllers(childAbortController);
+    const result = runTask(async () => {
+      validateActive(parentAbortSignal);
+      validateActive(childAbortController.signal);
+      const result2 = await taskExecutor({
+        pause: createPause(childAbortController.signal),
+        delay: createDelay(childAbortController.signal),
+        signal: childAbortController.signal
+      });
+      validateActive(childAbortController.signal);
+      return result2;
+    }, () => childAbortController.abort(taskCompleted));
+    if (opts?.autoJoin) {
+      parentBlockingPromises.push(result.catch(noop2));
+    }
+    return {
+      result: createPause(parentAbortSignal)(result),
+      cancel() {
+        childAbortController.abort(taskCancelled);
+      }
+    };
+  };
+};
+var createTakePattern = (startListening, signal) => {
+  const take = async (predicate, timeout) => {
+    validateActive(signal);
+    let unsubscribe = () => {
+    };
+    const tuplePromise = new Promise((resolve, reject) => {
+      let stopListening = startListening({
+        predicate,
+        effect: (action, listenerApi) => {
+          listenerApi.unsubscribe();
+          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
+        }
+      });
+      unsubscribe = () => {
+        stopListening();
+        reject();
+      };
+    });
+    const promises = [tuplePromise];
+    if (timeout != null) {
+      promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
+    }
+    try {
+      const output = await raceWithSignal(signal, Promise.race(promises));
+      validateActive(signal);
+      return output;
+    } finally {
+      unsubscribe();
+    }
+  };
+  return (predicate, timeout) => catchRejection(take(predicate, timeout));
+};
+var getListenerEntryPropsFrom = (options) => {
+  let {
+    type,
+    actionCreator,
+    matcher,
+    predicate,
+    effect
+  } = options;
+  if (type) {
+    predicate = createAction(type).match;
+  } else if (actionCreator) {
+    type = actionCreator.type;
+    predicate = actionCreator.match;
+  } else if (matcher) {
+    predicate = matcher;
+  } else if (predicate) {
+  } else {
+    throw new Error(false ? _formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
+  }
+  assertFunction(effect, "options.listener");
+  return {
+    predicate,
+    type,
+    effect
+  };
+};
+var createListenerEntry = /* @__PURE__ */ assign((options) => {
+  const {
+    type,
+    predicate,
+    effect
+  } = getListenerEntryPropsFrom(options);
+  const entry = {
+    id: nanoid(),
+    effect,
+    type,
+    predicate,
+    pending: /* @__PURE__ */ new Set(),
+    unsubscribe: () => {
+      throw new Error(false ? _formatProdErrorMessage2(22) : "Unsubscribe not initialized");
+    }
+  };
+  return entry;
+}, {
+  withTypes: () => createListenerEntry
+});
+var findListenerEntry = (listenerMap, options) => {
+  const {
+    type,
+    effect,
+    predicate
+  } = getListenerEntryPropsFrom(options);
+  return Array.from(listenerMap.values()).find((entry) => {
+    const matchPredicateOrType = typeof type === "string" ? entry.type === type : entry.predicate === predicate;
+    return matchPredicateOrType && entry.effect === effect;
+  });
+};
+var cancelActiveListeners = (entry) => {
+  entry.pending.forEach((controller) => {
+    controller.abort(listenerCancelled);
+  });
+};
+var createClearListenerMiddleware = (listenerMap, executingListeners) => {
+  return () => {
+    for (const listener2 of executingListeners.keys()) {
+      cancelActiveListeners(listener2);
+    }
+    listenerMap.clear();
+  };
+};
+var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
+  try {
+    errorHandler(errorToNotify, errorInfo);
+  } catch (errorHandlerError) {
+    setTimeout(() => {
+      throw errorHandlerError;
+    }, 0);
+  }
+};
+var addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), {
+  withTypes: () => addListener
+});
+var clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
+var removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), {
+  withTypes: () => removeListener
+});
+var defaultErrorHandler = (...args) => {
+  console.error(`${alm}/error`, ...args);
+};
+var createListenerMiddleware = (middlewareOptions = {}) => {
+  const listenerMap = /* @__PURE__ */ new Map();
+  const executingListeners = /* @__PURE__ */ new Map();
+  const trackExecutingListener = (entry) => {
+    const count = executingListeners.get(entry) ?? 0;
+    executingListeners.set(entry, count + 1);
+  };
+  const untrackExecutingListener = (entry) => {
+    const count = executingListeners.get(entry) ?? 1;
+    if (count === 1) {
+      executingListeners.delete(entry);
+    } else {
+      executingListeners.set(entry, count - 1);
+    }
+  };
+  const {
+    extra,
+    onError = defaultErrorHandler
+  } = middlewareOptions;
+  assertFunction(onError, "onError");
+  const insertEntry = (entry) => {
+    entry.unsubscribe = () => listenerMap.delete(entry.id);
+    listenerMap.set(entry.id, entry);
+    return (cancelOptions) => {
+      entry.unsubscribe();
+      if (cancelOptions?.cancelActive) {
+        cancelActiveListeners(entry);
+      }
+    };
+  };
+  const startListening = (options) => {
+    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options);
+    return insertEntry(entry);
+  };
+  assign(startListening, {
+    withTypes: () => startListening
+  });
+  const stopListening = (options) => {
+    const entry = findListenerEntry(listenerMap, options);
+    if (entry) {
+      entry.unsubscribe();
+      if (options.cancelActive) {
+        cancelActiveListeners(entry);
+      }
+    }
+    return !!entry;
+  };
+  assign(stopListening, {
+    withTypes: () => stopListening
+  });
+  const notifyListener = async (entry, action, api, getOriginalState) => {
+    const internalTaskController = new AbortController();
+    const take = createTakePattern(startListening, internalTaskController.signal);
+    const autoJoinPromises = [];
+    try {
+      entry.pending.add(internalTaskController);
+      trackExecutingListener(entry);
+      await Promise.resolve(entry.effect(
+        action,
+        // Use assign() rather than ... to avoid extra helper functions added to bundle
+        assign({}, api, {
+          getOriginalState,
+          condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
+          take,
+          delay: createDelay(internalTaskController.signal),
+          pause: createPause(internalTaskController.signal),
+          extra,
+          signal: internalTaskController.signal,
+          fork: createFork(internalTaskController.signal, autoJoinPromises),
+          unsubscribe: entry.unsubscribe,
+          subscribe: () => {
+            listenerMap.set(entry.id, entry);
+          },
+          cancelActiveListeners: () => {
+            entry.pending.forEach((controller, _, set) => {
+              if (controller !== internalTaskController) {
+                controller.abort(listenerCancelled);
+                set.delete(controller);
+              }
+            });
+          },
+          cancel: () => {
+            internalTaskController.abort(listenerCancelled);
+            entry.pending.delete(internalTaskController);
+          },
+          throwIfCancelled: () => {
+            validateActive(internalTaskController.signal);
+          }
+        })
+      ));
+    } catch (listenerError) {
+      if (!(listenerError instanceof TaskAbortError)) {
+        safelyNotifyError(onError, listenerError, {
+          raisedBy: "effect"
+        });
+      }
+    } finally {
+      await Promise.all(autoJoinPromises);
+      internalTaskController.abort(listenerCompleted);
+      untrackExecutingListener(entry);
+      entry.pending.delete(internalTaskController);
+    }
+  };
+  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);
+  const middleware = (api) => (next) => (action) => {
+    if (!(0, import_redux.isAction)(action)) {
+      return next(action);
+    }
+    if (addListener.match(action)) {
+      return startListening(action.payload);
+    }
+    if (clearAllListeners.match(action)) {
+      clearListenerMiddleware();
+      return;
+    }
+    if (removeListener.match(action)) {
+      return stopListening(action.payload);
+    }
+    let originalState = api.getState();
+    const getOriginalState = () => {
+      if (originalState === INTERNAL_NIL_TOKEN) {
+        throw new Error(false ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);
+      }
+      return originalState;
+    };
+    let result;
+    try {
+      result = next(action);
+      if (listenerMap.size > 0) {
+        const currentState = api.getState();
+        const listenerEntries = Array.from(listenerMap.values());
+        for (const entry of listenerEntries) {
+          let runListener = false;
+          try {
+            runListener = entry.predicate(action, currentState, originalState);
+          } catch (predicateError) {
+            runListener = false;
+            safelyNotifyError(onError, predicateError, {
+              raisedBy: "predicate"
+            });
+          }
+          if (!runListener) {
+            continue;
+          }
+          notifyListener(entry, action, api, getOriginalState);
+        }
+      }
+    } finally {
+      originalState = INTERNAL_NIL_TOKEN;
+    }
+    return result;
+  };
+  return {
+    middleware,
+    startListening,
+    stopListening,
+    clearListeners: clearListenerMiddleware
+  };
+};
+
+// src/dynamicMiddleware/index.ts
+var createMiddlewareEntry = (middleware) => ({
+  middleware,
+  applied: /* @__PURE__ */ new Map()
+});
+var matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;
+var createDynamicMiddleware = () => {
+  const instanceId = nanoid();
+  const middlewareMap = /* @__PURE__ */ new Map();
+  const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
+    payload: middlewares,
+    meta: {
+      instanceId
+    }
+  })), {
+    withTypes: () => withMiddleware
+  });
+  const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
+    middlewares.forEach((middleware2) => {
+      getOrInsertComputed(middlewareMap, middleware2, createMiddlewareEntry);
+    });
+  }, {
+    withTypes: () => addMiddleware
+  });
+  const getFinalMiddleware = (api) => {
+    const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => getOrInsertComputed(entry.applied, api, entry.middleware));
+    return (0, import_redux.compose)(...appliedMiddleware);
+  };
+  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
+  const middleware = (api) => (next) => (action) => {
+    if (isWithMiddleware(action)) {
+      addMiddleware(...action.payload);
+      return api.dispatch;
+    }
+    return getFinalMiddleware(api)(next)(action);
+  };
+  return {
+    middleware,
+    addMiddleware,
+    withMiddleware,
+    instanceId
+  };
+};
+
+// src/combineSlices.ts
+var import_redux2 = require("redux");
+var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
+var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
+var ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
+var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
+var stateProxyMap = /* @__PURE__ */ new WeakMap();
+var createStateProxy = (state, reducerMap, initialStateCache) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {
+  get: (target, prop, receiver) => {
+    if (prop === ORIGINAL_STATE) return target;
+    const result = Reflect.get(target, prop, receiver);
+    if (typeof result === "undefined") {
+      const cached = initialStateCache[prop];
+      if (typeof cached !== "undefined") return cached;
+      const reducer = reducerMap[prop];
+      if (reducer) {
+        const reducerResult = reducer(void 0, {
+          type: nanoid()
+        });
+        if (typeof reducerResult === "undefined") {
+          throw new Error(false ? _formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
+        }
+        initialStateCache[prop] = reducerResult;
+        return reducerResult;
+      }
+    }
+    return result;
+  }
+}));
+var original = (state) => {
+  if (!isStateProxy(state)) {
+    throw new Error(false ? _formatProdErrorMessage2(25) : "original must be used on state Proxy");
+  }
+  return state[ORIGINAL_STATE];
+};
+var emptyObject = {};
+var noopReducer = (state = emptyObject) => state;
+function combineSlices(...slices) {
+  const reducerMap = Object.fromEntries(getReducers(slices));
+  const getReducer = () => Object.keys(reducerMap).length ? (0, import_redux2.combineReducers)(reducerMap) : noopReducer;
+  let reducer = getReducer();
+  function combinedReducer(state, action) {
+    return reducer(state, action);
+  }
+  combinedReducer.withLazyLoadedSlices = () => combinedReducer;
+  const initialStateCache = {};
+  const inject = (slice, config = {}) => {
+    const {
+      reducerPath,
+      reducer: reducerToInject
+    } = slice;
+    const currentReducer = reducerMap[reducerPath];
+    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
+      if (typeof process !== "undefined" && true) {
+        console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
+      }
+      return combinedReducer;
+    }
+    if (config.overrideExisting && currentReducer !== reducerToInject) {
+      delete initialStateCache[reducerPath];
+    }
+    reducerMap[reducerPath] = reducerToInject;
+    reducer = getReducer();
+    return combinedReducer;
+  };
+  const selector = Object.assign(function makeSelector(selectorFn, selectState) {
+    return function selector2(state, ...args) {
+      return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap, initialStateCache), ...args);
+    };
+  }, {
+    original
+  });
+  return Object.assign(combinedReducer, {
+    inject,
+    selector
+  });
+}
+
+// src/formatProdErrorMessage.ts
+function formatProdErrorMessage(code) {
+  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+  ReducerType,
+  SHOULD_AUTOBATCH,
+  TaskAbortError,
+  Tuple,
+  addListener,
+  asyncThunkCreator,
+  autoBatchEnhancer,
+  buildCreateSlice,
+  clearAllListeners,
+  combineSlices,
+  configureStore,
+  createAction,
+  createActionCreatorInvariantMiddleware,
+  createAsyncThunk,
+  createDraftSafeSelector,
+  createDraftSafeSelectorCreator,
+  createDynamicMiddleware,
+  createEntityAdapter,
+  createImmutableStateInvariantMiddleware,
+  createListenerMiddleware,
+  createNextState,
+  createReducer,
+  createSelector,
+  createSelectorCreator,
+  createSerializableStateInvariantMiddleware,
+  createSlice,
+  current,
+  findNonSerializableValue,
+  formatProdErrorMessage,
+  freeze,
+  isActionCreator,
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isDraft,
+  isFluxStandardAction,
+  isFulfilled,
+  isImmutableDefault,
+  isPending,
+  isPlain,
+  isRejected,
+  isRejectedWithValue,
+  lruMemoize,
+  miniSerializeError,
+  nanoid,
+  original,
+  prepareAutoBatched,
+  removeListener,
+  unwrapResult,
+  weakMapMemoize,
+  ...require("redux")
+});
+//# sourceMappingURL=redux-toolkit.development.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/index.ts","../../src/immerImports.ts","../../src/reselectImports.ts","../../src/createDraftSafeSelector.ts","../../src/reduxImports.ts","../../src/devtoolsExtension.ts","../../src/getDefaultMiddleware.ts","../../src/tsHelpers.ts","../../src/createAction.ts","../../src/actionCreatorInvariantMiddleware.ts","../../src/utils.ts","../../src/immutableStateInvariantMiddleware.ts","../../src/serializableStateInvariantMiddleware.ts","../../src/autoBatchEnhancer.ts","../../src/getDefaultEnhancers.ts","../../src/configureStore.ts","../../src/mapBuilders.ts","../../src/createReducer.ts","../../src/matchers.ts","../../src/nanoid.ts","../../src/createAsyncThunk.ts","../../src/createSlice.ts","../../src/entities/entity_state.ts","../../src/entities/state_selectors.ts","../../src/entities/state_adapter.ts","../../src/entities/utils.ts","../../src/entities/unsorted_state_adapter.ts","../../src/entities/sorted_state_adapter.ts","../../src/entities/create_adapter.ts","../../src/listenerMiddleware/exceptions.ts","../../src/listenerMiddleware/utils.ts","../../src/listenerMiddleware/task.ts","../../src/listenerMiddleware/index.ts","../../src/dynamicMiddleware/index.ts","../../src/combineSlices.ts","../../src/formatProdErrorMessage.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage';\nexport * from 'redux';\nexport { freeze, original } from 'immer';\nexport { createNextState, current, isDraft } from './immerImports';\nexport type { Draft, WritableDraft } from 'immer';\nexport { createSelector, lruMemoize } from 'reselect';\nexport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport type { Selector, OutputSelector } from 'reselect';\nexport { createDraftSafeSelector, createDraftSafeSelectorCreator } from './createDraftSafeSelector';\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';\nexport {\n// js\nconfigureStore } from './configureStore';\nexport type {\n// types\nConfigureStoreOptions, EnhancedStore } from './configureStore';\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension';\nexport {\n// js\ncreateAction, isActionCreator, isFSA as isFluxStandardAction } from './createAction';\nexport type {\n// types\nPayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction } from './createAction';\nexport {\n// js\ncreateReducer } from './createReducer';\nexport type {\n// types\nActions, CaseReducer, CaseReducers } from './createReducer';\nexport {\n// js\ncreateSlice, buildCreateSlice, asyncThunkCreator, ReducerType } from './createSlice';\nexport type {\n// types\nCreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, ReducerCreators, SliceSelectors } from './createSlice';\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nexport {\n// js\ncreateImmutableStateInvariantMiddleware, isImmutableDefault } from './immutableStateInvariantMiddleware';\nexport type {\n// types\nImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\nexport {\n// js\ncreateSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nSerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nActionReducerMapBuilder, AsyncThunkReducers } from './mapBuilders';\nexport { Tuple } from './utils';\nexport { createEntityAdapter } from './entities/create_adapter';\nexport type { EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer } from './entities/models';\nexport { createAsyncThunk, unwrapResult, miniSerializeError } from './createAsyncThunk';\nexport type { AsyncThunk, AsyncThunkConfig, AsyncThunkDispatchConfig, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, GetState, GetThunkAPI, SerializedError, CreateAsyncThunkFunction } from './createAsyncThunk';\nexport {\n// js\nisAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue } from './matchers';\nexport type {\n// types\nActionMatchingAllOf, ActionMatchingAnyOf } from './matchers';\nexport { nanoid } from './nanoid';\nexport type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult } from './listenerMiddleware/index';\nexport type { AnyListenerPredicate } from './listenerMiddleware/types';\nexport { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError } from './listenerMiddleware/index';\nexport type { AddMiddleware, DynamicDispatch, DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './dynamicMiddleware/types';\nexport { createDynamicMiddleware } from './dynamicMiddleware/index';\nexport { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer } from './autoBatchEnhancer';\nexport type { AutoBatchOptions } from './autoBatchEnhancer';\nexport { combineSlices } from './combineSlices';\nexport type { CombinedSliceReducer, WithSlice, WithSlicePreloadedState } from './combineSlices';\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers';\nexport { formatProdErrorMessage } from './formatProdErrorMessage';","export { current, isDraft, produce as createNextState, isDraftable, setUseStrictIteration } from 'immer';","export { createSelectorCreator, weakMapMemoize } from 'reselect';","import { current, isDraft } from './immerImports';\nimport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (...args: unknown[]) => {\n  const createSelector = (createSelectorCreator as any)(...args);\n  const createDraftSafeSelector = Object.assign((...args: unknown[]) => {\n    const selector = createSelector(...args);\n    const wrappedSelector = (value: unknown, ...rest: unknown[]) => selector(isDraft(value) ? current(value) : value, ...rest);\n    Object.assign(wrappedSelector, selector);\n    return wrappedSelector as any;\n  }, {\n    withTypes: () => createDraftSafeSelector\n  });\n  return createDraftSafeSelector;\n};\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector = /* @__PURE__ */\ncreateDraftSafeSelectorCreator(weakMapMemoize);","export { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from 'redux';","import type { Action, ActionCreator, StoreEnhancer } from 'redux';\nimport { compose } from './reduxImports';\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string;\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | {\n    [key: string]: ActionCreator<any>;\n  };\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number;\n  /**\n   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\n   *\n   * @default 50\n   */\n  maxAge?: number;\n  /**\n   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?: boolean | {\n    /**\n     * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n     * - `false` - will handle also circular references.\n     * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n     * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n     *   For each of them you can indicate if to include (by setting as `true`).\n     *   For `function` key you can also specify a custom function which handles serialization.\n     *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n     */\n    options?: undefined | boolean | {\n      date?: true;\n      regex?: true;\n      undefined?: true;\n      error?: true;\n      symbol?: true;\n      map?: true;\n      set?: true;\n      function?: true | ((fn: (...args: any[]) => any) => string);\n    };\n    /**\n     * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\n     * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n     * key. So you can deserialize it back while importing or persisting data.\n     * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\n     */\n    replacer?: (key: string, value: unknown) => any;\n    /**\n     * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n     * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n     * as an example on how to serialize special data types and get them back.\n     */\n    reviver?: (key: string, value: unknown) => any;\n    /**\n     * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n     * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n     * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n     */\n    immutable?: any;\n    /**\n     * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n     */\n    refs?: any;\n  };\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A;\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S;\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[];\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[];\n  /**\n   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean;\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean;\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string;\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean;\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean;\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean;\n  /**\n   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean;\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean;\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean;\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean;\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom';\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom';\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean;\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean;\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean;\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean;\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean;\n  };\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string);\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number;\n}\ntype Compose = typeof compose;\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose;\n  <StoreExt extends {}>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\n  if (arguments.length === 0) return undefined;\n  if (typeof arguments[0] === 'object') return compose;\n  return compose.apply(null, arguments as any as Function[]);\n};\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>;\n} = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION__ : function () {\n  return function (noop) {\n    return noop;\n  };\n};","import type { Middleware, UnknownAction } from 'redux';\nimport type { ThunkMiddleware } from 'redux-thunk';\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk';\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware';\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware';\nimport type { ExcludeFromTuple } from './tsHelpers';\nimport { Tuple } from './utils';\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean';\n}\ninterface ThunkOptions<E = any> {\n  extraArgument: E;\n}\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions;\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;\n}\nexport type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {\n  thunk: false;\n} ? never : O extends {\n  thunk: {\n    extraArgument: infer E;\n  };\n} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;\nexport type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {\n  thunk: true;\n  immutableCheck: true;\n  serializableCheck: true;\n  actionCreatorCheck: true;\n}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;\nexport const buildGetDefaultMiddleware = <S = any,>(): GetDefaultMiddleware<S> => function getDefaultMiddleware(options) {\n  const {\n    thunk = true,\n    immutableCheck = true,\n    serializableCheck = true,\n    actionCreatorCheck = true\n  } = options ?? {};\n  let middlewareArray = new Tuple<Middleware[]>();\n  if (thunk) {\n    if (isBoolean(thunk)) {\n      middlewareArray.push(thunkMiddleware);\n    } else {\n      middlewareArray.push(withExtraArgument(thunk.extraArgument));\n    }\n  }\n  if (process.env.NODE_ENV !== 'production') {\n    if (immutableCheck) {\n      /* PROD_START_REMOVE_UMD */\n      let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(immutableCheck)) {\n        immutableOptions = immutableCheck;\n      }\n      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n      /* PROD_STOP_REMOVE_UMD */\n    }\n    if (serializableCheck) {\n      let serializableOptions: SerializableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(serializableCheck)) {\n        serializableOptions = serializableCheck;\n      }\n      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n    }\n    if (actionCreatorCheck) {\n      let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {};\n      if (!isBoolean(actionCreatorCheck)) {\n        actionCreatorOptions = actionCreatorCheck;\n      }\n      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n    }\n  }\n  return middlewareArray as any;\n};","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport { isAction } from './reduxImports';\nimport type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<P = void, T extends string = string, M = never, E = never> = {\n  payload: P;\n  type: T;\n} & ([M] extends [never] ? {} : {\n  meta: M;\n}) & ([E] extends [never] ? {} : {\n  error: E;\n});\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> = ((...args: any[]) => {\n  payload: P;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  error: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n  error: any;\n});\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {\n  error: infer E;\n} ? E : never, ReturnType<PA> extends {\n  meta: infer M;\n} ? M : never> : void;\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T;\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>;\n};\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>;\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>;\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>;\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>,\n// else\nIsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>,\n// else\nIfVoid<P, ActionCreatorWithoutPayload<T>,\n// else\nIfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>,\n// else\nActionCreatorWithPayload<P, T>>>>>>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args);\n      if (!prepared) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(0) : 'prepareAction did not return an object');\n      }\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && {\n          meta: prepared.meta\n        }),\n        ...('error' in prepared && {\n          error: prepared.error\n        })\n      };\n    }\n    return {\n      type,\n      payload: args[0]\n    };\n  }\n  actionCreator.toString = () => `${type}`;\n  actionCreator.type = type;\n  actionCreator.match = (action: unknown): action is PayloadAction => isAction(action) && action.type === type;\n  return actionCreator;\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function {\n  return typeof action === 'function' && 'type' in action &&\n  // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n  hasMatchFunction(action as any);\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string;\n  payload?: unknown;\n  error?: unknown;\n  meta?: unknown;\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1;\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends ((...args: any[]) => any) ? True : False;","import type { Middleware } from 'redux';\nimport { isActionCreator as isRTKAction } from './createAction';\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & {\n    type?: unknown;\n  };\n}\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : [];\n  const actionName = splitType[splitType.length - 1] || 'actionCreator';\n  return `Detected an action creator with type \"${type || 'unknown'}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nexport function createActionCreatorInvariantMiddleware(options: ActionCreatorInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  }\n  const {\n    isActionCreator = isRTKAction\n  } = options;\n  return () => next => action => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type));\n    }\n    return next(action);\n  };\n}","import { createNextState, isDraftable } from './immerImports';\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0;\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now();\n      try {\n        return fn();\n      } finally {\n        const finished = Date.now();\n        elapsed += finished - started;\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n      }\n    }\n  };\n}\nexport function delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {\n  constructor(length: number);\n  constructor(...items: Items);\n  constructor(...items: any[]) {\n    super(...items);\n    Object.setPrototypeOf(this, Tuple.prototype);\n  }\n  static override get [Symbol.species]() {\n    return Tuple as any;\n  }\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr);\n  }\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this));\n    }\n    return new Tuple(...arr.concat(this));\n  }\n}\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val;\n}\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | PromiseLike<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve: any;\n  let reject: any;\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve,\n    reject\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Middleware } from 'redux';\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware';\nimport { getTimeMeasureUtils } from './utils';\ntype EntryProcessor = (key: string, value: any) => any;\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value);\n}\nexport function trackForMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths | undefined, obj: any) {\n  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);\n    }\n  };\n}\ninterface TrackedProperty {\n  value: any;\n  children: Record<string, any>;\n}\nfunction trackProperties(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], obj: Record<string, any>, path: string = '', checkedObjects: Set<Record<string, any>> = new Set()) {\n  const tracked: Partial<TrackedProperty> = {\n    value: obj\n  };\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj);\n    tracked.children = {};\n    const hasIgnoredPaths = ignoredPaths.length > 0;\n    for (const key in obj) {\n      const nestedPath = path ? path + '.' + key : key;\n      if (hasIgnoredPaths) {\n        const hasMatches = ignoredPaths.some(ignored => {\n          if (ignored instanceof RegExp) {\n            return ignored.test(nestedPath);\n          }\n          return nestedPath === ignored;\n        });\n        if (hasMatches) {\n          continue;\n        }\n      }\n      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);\n    }\n  }\n  return tracked as TrackedProperty;\n}\nfunction detectMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, path: string = ''): {\n  wasMutated: boolean;\n  path?: string;\n} {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined;\n  const sameRef = prevObj === obj;\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return {\n      wasMutated: true,\n      path\n    };\n  }\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return {\n      wasMutated: false\n    };\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {};\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true;\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true;\n  }\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n    if (result.wasMutated) {\n      return result;\n    }\n  }\n  return {\n    wasMutated: false\n  };\n}\ntype IsImmutableFunc = (value: any) => boolean;\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc;\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths;\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number;\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(options: ImmutableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    function stringify(obj: any, serializer?: EntryProcessor, indent?: string | number, decycler?: EntryProcessor): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\n    }\n    function getSerialize(serializer?: EntryProcessor, decycler?: EntryProcessor): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = [];\n      if (!decycler) decycler = function (_: string, value: any) {\n        if (stack[0] === value) return '[Circular ~]';\n        return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n      };\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this);\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value);\n        } else stack.push(value);\n        return serializer == null ? value : serializer.call(this, key, value);\n      };\n    }\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32\n    } = options;\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n    return ({\n      getState\n    }) => {\n      let state = getState();\n      let tracker = track(state);\n      let result;\n      return next => action => {\n        const measureUtils = getTimeMeasureUtils(warnAfter, 'ImmutableStateInvariantMiddleware');\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ''}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        const dispatchedAction = next(action);\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ''}. Take a look at the reducer(s) handling the action ${stringify(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n        return dispatchedAction;\n      };\n    };\n  }\n}","import type { Middleware } from 'redux';\nimport { isAction, isPlainObject } from './reduxImports';\nimport { getTimeMeasureUtils } from './utils';\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val;\n  return val == null || type === 'string' || type === 'boolean' || type === 'number' || Array.isArray(val) || isPlainObject(val);\n}\ninterface NonSerializableValue {\n  keyPath: string;\n  value: unknown;\n}\nexport type IgnorePaths = readonly (string | RegExp)[];\n\n/**\n * @public\n */\nexport function findNonSerializableValue(value: unknown, path: string = '', isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], cache?: WeakSet<object>): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false;\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value\n    };\n  }\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  if (cache?.has(value)) return false;\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue\n      };\n    }\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n      if (foundNestedSerializable) {\n        return foundNestedSerializable;\n      }\n    }\n  }\n  if (cache && isNestedFrozen(value)) cache.add(value);\n  return false;\n}\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false;\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue;\n    if (!isNestedFrozen(nestedValue)) return false;\n  }\n  return true;\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean;\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][];\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[];\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number;\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean;\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean;\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean;\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(options: SerializableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false\n    } = options;\n    const cache: WeakSet<object> | undefined = !disableCache && WeakSet ? new WeakSet() : undefined;\n    return storeAPI => next => action => {\n      if (!isAction(action)) {\n        return next(action);\n      }\n      const result = next(action);\n      const measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type as any) !== -1)) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(action, '', isSerializable, getEntries, ignoredActionPaths, cache);\n          if (foundActionNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundActionNonSerializableValue;\n            console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, '\\nTake a look at the logic that dispatched this action: ', action, '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)');\n          }\n        });\n      }\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState();\n          const foundStateNonSerializableValue = findNonSerializableValue(state, '', isSerializable, getEntries, ignoredPaths, cache);\n          if (foundStateNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundStateNonSerializableValue;\n            console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n      }\n      return result;\n    };\n  }\n}","import type { StoreEnhancer } from 'redux';\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch';\nexport const prepareAutoBatched = <T,>() => (payload: T): {\n  payload: T;\n  meta: unknown;\n} => ({\n  payload,\n  meta: {\n    [SHOULD_AUTOBATCH]: true\n  }\n});\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout);\n  };\n};\nexport type AutoBatchOptions = {\n  type: 'tick';\n} | {\n  type: 'timer';\n  timeout: number;\n} | {\n  type: 'raf';\n} | {\n  type: 'callback';\n  queueNotification: (notify: () => void) => void;\n};\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer = (options: AutoBatchOptions = {\n  type: 'raf'\n}): StoreEnhancer => next => (...args) => {\n  const store = next(...args);\n  let notifying = true;\n  let shouldNotifyAtEndOfTick = false;\n  let notificationQueued = false;\n  const listeners = new Set<() => void>();\n  const queueCallback = options.type === 'tick' ? queueMicrotask : options.type === 'raf' ?\n  // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n  typeof window !== 'undefined' && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === 'callback' ? options.queueNotification : createQueueWithTimer(options.timeout);\n  const notifyListeners = () => {\n    // We're running at the end of the event loop tick.\n    // Run the real listener callbacks to actually update the UI.\n    notificationQueued = false;\n    if (shouldNotifyAtEndOfTick) {\n      shouldNotifyAtEndOfTick = false;\n      listeners.forEach(l => l());\n    }\n  };\n  return Object.assign({}, store, {\n    // Override the base `store.subscribe` method to keep original listeners\n    // from running if we're delaying notifications\n    subscribe(listener: () => void) {\n      // Each wrapped listener will only call the real listener if\n      // the `notifying` flag is currently active when it's called.\n      // This lets the base store work as normal, while the actual UI\n      // update becomes controlled by this enhancer.\n      const wrappedListener: typeof listener = () => notifying && listener();\n      const unsubscribe = store.subscribe(wrappedListener);\n      listeners.add(listener);\n      return () => {\n        unsubscribe();\n        listeners.delete(listener);\n      };\n    },\n    // Override the base `store.dispatch` method so that we can check actions\n    // for the `shouldAutoBatch` flag and determine if batching is active\n    dispatch(action: any) {\n      try {\n        // If the action does _not_ have the `shouldAutoBatch` flag,\n        // we resume/continue normal notify-after-each-dispatch behavior\n        notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n        // If a `notifyListeners` microtask was queued, you can't cancel it.\n        // Instead, we set a flag so that it's a no-op when it does run\n        shouldNotifyAtEndOfTick = !notifying;\n        if (shouldNotifyAtEndOfTick) {\n          // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n          // a microtask to notify listeners at the end of the event loop tick.\n          // Make sure we only enqueue this _once_ per tick.\n          if (!notificationQueued) {\n            notificationQueued = true;\n            queueCallback(notifyListeners);\n          }\n        }\n        // Go ahead and process the action as usual, including reducers.\n        // If normal notification behavior is enabled, the store will notify\n        // all of its own listeners, and the wrapper callbacks above will\n        // see `notifying` is true and pass on to the real listener callbacks.\n        // If we're \"batching\" behavior, then the wrapped callbacks will\n        // bail out, causing the base store notification behavior to be no-ops.\n        return store.dispatch(action);\n      } finally {\n        // Assume we're back to normal behavior after each action\n        notifying = true;\n      }\n    }\n  });\n};","import type { StoreEnhancer } from 'redux';\nimport type { AutoBatchOptions } from './autoBatchEnhancer';\nimport { autoBatchEnhancer } from './autoBatchEnhancer';\nimport { Tuple } from './utils';\nimport type { Middlewares } from './configureStore';\nimport type { ExtractDispatchExtensions } from './tsHelpers';\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions;\n};\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>]>;\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>,>(middlewareEnhancer: StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>): GetDefaultEnhancers<M> => function getDefaultEnhancers(options) {\n  const {\n    autoBatch = true\n  } = options ?? {};\n  let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer);\n  if (autoBatch) {\n    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined));\n  }\n  return enhancerArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Reducer, ReducersMapObject, Middleware, Action, StoreEnhancer, Store, UnknownAction } from 'redux';\nimport { applyMiddleware, createStore, compose, combineReducers, isPlainObject } from './reduxImports';\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';\nimport { composeWithDevTools } from './devtoolsExtension';\nimport type { ThunkMiddlewareFor, GetDefaultMiddleware } from './getDefaultMiddleware';\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware';\nimport type { ExtractDispatchExtensions, ExtractStoreExtensions, ExtractStateExtensions, UnknownIfNonSpecific } from './tsHelpers';\nimport type { Tuple } from './utils';\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers';\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers';\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions;\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean;\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P;\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;\n}\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;\ntype Enhancers = ReadonlyArray<StoreEnhancer>;\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>, StoreEnhancer]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>();\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined\n  } = options || {};\n  let rootReducer: Reducer<S, A, P>;\n  if (typeof reducer === 'function') {\n    rootReducer = reducer;\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>;\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(1) : '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\n  }\n  if (process.env.NODE_ENV !== 'production' && middleware && typeof middleware !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(2) : '`middleware` field must be a callback');\n  }\n  let finalMiddleware: Tuple<Middlewares<S>>;\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware);\n    if (process.env.NODE_ENV !== 'production' && !Array.isArray(finalMiddleware)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(3) : 'when using a middleware builder function, an array of middleware must be returned');\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware();\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(4) : 'each middleware provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>();\n    finalMiddleware.forEach(middleware => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(42) : 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.');\n      }\n      middlewareReferences.add(middleware);\n    });\n  }\n  let finalCompose = compose;\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools)\n    });\n  }\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer);\n  if (process.env.NODE_ENV !== 'production' && enhancers && typeof enhancers !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(5) : '`enhancers` field must be a callback');\n  }\n  let storeEnhancers = typeof enhancers === 'function' ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(6) : '`enhancers` callback must return an array');\n  }\n  if (process.env.NODE_ENV !== 'production' && storeEnhancers.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(7) : 'each enhancer provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n    console.error('middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`');\n  }\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers);\n  return createStore(rootReducer, preloadedState as P, composedEnhancer);\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7 } from \"@reduxjs/toolkit\";\nimport type { Action } from 'redux';\nimport type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';\nimport type { TypeGuard } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk';\nexport type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;\n  rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;\n  fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;\n  settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;\n};\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>;\n  type: Type;\n};\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;\n\n  /**\n   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.\n   * @remarks\n   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param asyncThunk - The async thunk action creator itself.\n   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.\n   * @example\n  ```ts no-transpile\n  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'\n  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {\n  const response = await fetch(`https://reqres.in/api/users/${id}`)\n  return (await response.json()).data\n  })\n  const reducer = createReducer(initialState, (builder) => {\n  builder.addAsyncThunk(fetchUserById, {\n    pending: (state, action) => {\n      state.fetchUserById.loading = 'pending'\n    },\n    fulfilled: (state, action) => {\n      state.fetchUserById.data = action.payload\n    },\n    rejected: (state, action) => {\n      state.fetchUserById.error = action.error\n    },\n    settled: (state, action) => {\n      state.fetchUserById.loading = action.meta.requestStatus\n    },\n  })\n  })\n   */\n  addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n  ```ts\n  import {\n  createAction,\n  createReducer,\n  AsyncThunk,\n  UnknownAction,\n  } from \"@reduxjs/toolkit\";\n  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n  type PendingAction = ReturnType<GenericAsyncThunk[\"pending\"]>;\n  type RejectedAction = ReturnType<GenericAsyncThunk[\"rejected\"]>;\n  type FulfilledAction = ReturnType<GenericAsyncThunk[\"fulfilled\"]>;\n  const initialState: Record<string, string> = {};\n  const resetAction = createAction(\"reset-tracked-loading-state\");\n  function isPendingAction(action: UnknownAction): action is PendingAction {\n  return typeof action.type === \"string\" && action.type.endsWith(\"/pending\");\n  }\n  const reducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(resetAction, () => initialState)\n    // matcher can be defined outside as a type predicate function\n    .addMatcher(isPendingAction, (state, action) => {\n      state[action.meta.requestId] = \"pending\";\n    })\n    .addMatcher(\n      // matcher can be defined inline as a type predicate function\n      (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"rejected\";\n      }\n    )\n    // matcher can just return boolean and the matcher can receive a generic argument\n    .addMatcher<FulfilledAction>(\n      (action) => action.type.endsWith(\"/fulfilled\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"fulfilled\";\n      }\n    );\n  });\n  ```\n   */\n  addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n  ```ts\n  import { createReducer } from '@reduxjs/toolkit'\n  const initialState = { otherActions: 0 }\n  const reducer = createReducer(initialState, builder => {\n  builder\n    // .addCase(...)\n    // .addMatcher(...)\n    .addDefaultCase((state, action) => {\n      state.otherActions++\n    })\n  })\n  ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {};\n}\nexport function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [CaseReducers<S, any>, ActionMatcherDescriptionCollection<S>, CaseReducer<S, Action> | undefined] {\n  const actionsMap: CaseReducers<S, any> = {};\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = [];\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined;\n  const builder = {\n    addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<S>) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(26) : '`builder.addCase` should only be called before calling `builder.addMatcher`');\n        }\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(27) : '`builder.addCase` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n      if (!type) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(28) : '`builder.addCase` cannot be called with an empty action type');\n      }\n      if (type in actionsMap) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(29) : '`builder.addCase` cannot be called with two reducers for the same action type ' + `'${type}'`);\n      }\n      actionsMap[type] = reducer;\n      return builder;\n    },\n    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>) {\n      if (process.env.NODE_ENV !== 'production') {\n        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(43) : '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;\n      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;\n      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;\n      if (reducers.settled) actionMatchers.push({\n        matcher: asyncThunk.settled,\n        reducer: reducers.settled\n      });\n      return builder;\n    },\n    addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<S, A extends Action ? A : A & Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(30) : '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      actionMatchers.push({\n        matcher,\n        reducer\n      });\n      return builder;\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(31) : '`builder.addDefaultCase` can only be called once');\n        }\n      }\n      defaultCaseReducer = reducer;\n      return builder;\n    }\n  };\n  builderCallback(builder);\n  return [actionsMap, actionMatchers, defaultCaseReducer];\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Draft } from 'immer';\nimport { createNextState, isDraft, isDraftable, setUseStrictIteration } from './immerImports';\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { ActionReducerMapBuilder } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { NoInfer, TypeGuard } from './tsHelpers';\nimport { freezeDraftable } from './utils';\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>;\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>;\n  reducer: CaseReducer<S, NoInfer<A>>;\n};\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;\nexport type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void };\nexport type NotFunction<T> = T extends Function ? never : T;\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function';\n}\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S;\n};\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n```ts\nimport {\n  createAction,\n  createReducer,\n  UnknownAction,\n  PayloadAction,\n} from \"@reduxjs/toolkit\";\n\nconst increment = createAction<number>(\"increment\");\nconst decrement = createAction<number>(\"decrement\");\n\nfunction isActionWithNumberPayload(\n  action: UnknownAction\n): action is PayloadAction<number> {\n  return typeof action.payload === \"number\";\n}\n\nconst reducer = createReducer(\n  {\n    counter: 0,\n    sumOfNumberPayloads: 0,\n    unhandledActions: 0,\n  },\n  (builder) => {\n    builder\n      .addCase(increment, (state, action) => {\n        // action is inferred correctly here\n        state.counter += action.payload;\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {\n        state.counter -= action.payload;\n      })\n      // You can apply a \"matcher function\" to incoming actions\n      .addMatcher(isActionWithNumberPayload, (state, action) => {})\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {});\n  }\n);\n```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n    }\n  }\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S;\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState());\n  } else {\n    const frozenInitialState = freezeDraftable(initialState);\n    getInitialState = () => frozenInitialState;\n  }\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n      matcher\n    }) => matcher(action)).map(({\n      reducer\n    }) => reducer)];\n    if (caseReducers.filter(cr => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer];\n    }\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S>; // We can assume this is already a draft\n          const result = caseReducer(draft, action);\n          if (result === undefined) {\n            return previousState;\n          }\n          return result as S;\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action);\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState;\n            }\n            throw Error('A case reducer on a non-draftable value must not return undefined');\n          }\n          return result as S;\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action);\n          });\n        }\n      }\n      return previousState;\n    }, state);\n  }\n  reducer.getInitialState = getInitialState;\n  return reducer as ReducerWithInitialState<S>;\n}","import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action);\n  } else {\n    return matcher(action);\n  }\n};\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]) {\n  if (!action || !action.meta) return false;\n  const hasValidRequestId = typeof action.meta.requestId === 'string';\n  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n  return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return typeof a[0] === 'function' && 'pending' in a[0] && 'fulfilled' in a[0] && 'rejected' in a[0];\n}\nexport type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction;\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.pending));\n}\nexport type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.rejected));\n}\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {\n  rejectValue: infer RejectedValue;\n}> ? {\n  payload: RejectedValue;\n} : unknown);\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue;\n  };\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0]);\n  }\n  return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.fulfilled));\n}\nexport type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;\nexport type AnyAsyncThunk = {\n  pending: {\n    match: (action: any) => action is any;\n  };\n  fulfilled: {\n    match: (action: any) => action is any;\n  };\n  rejected: {\n    match: (action: any) => action is any;\n  };\n};\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}","// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\n/**\n *\n * @public\n */\nexport let nanoid = (size = 21) => {\n  let id = '';\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size;\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[Math.random() * 64 | 0];\n  }\n  return id;\n};","import type { Dispatch, UnknownAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport type { ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport { isAnyOf } from './matchers';\nimport { nanoid } from './nanoid';\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown, SafePromise } from './tsHelpers';\nexport type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {\n  dispatch: D;\n  getState: () => S;\n  extra: E;\n  requestId: string;\n  signal: AbortSignal;\n  abort: (reason?: string) => void;\n  rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;\n  fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;\n};\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string;\n  message?: string;\n  stack?: string;\n  code?: string;\n}\nconst commonProperties: Array<keyof SerializedError> = ['name', 'message', 'stack', 'code'];\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue';\n  constructor(public readonly payload: Payload, public readonly meta: RejectedMeta) {}\n}\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta';\n  constructor(public readonly payload: Payload, public readonly meta: FulfilledMeta) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {};\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property];\n      }\n    }\n    return simpleError;\n  }\n  return {\n    message: String(value)\n  };\n};\nexport type AsyncThunkConfig = {\n  state?: unknown;\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;\n  extra?: unknown;\n  rejectValue?: unknown;\n  serializedErrorType?: unknown;\n  pendingMeta?: unknown;\n  fulfilledMeta?: unknown;\n  rejectedMeta?: unknown;\n};\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State;\n} ? State : unknown;\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends {\n  extra: infer Extra;\n} ? Extra : unknown;\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch;\n} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue;\n} ? RejectValue : unknown;\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta;\n} ? PendingMeta : unknown;\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta;\n} ? FulfilledMeta : unknown;\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta;\n} ? RejectedMeta : unknown;\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType;\n} ? GetSerializedErrorType : SerializedError;\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {\n  abort: (reason?: string) => void;\n  requestId: string;\n  arg: ThunkArg;\n  unwrap: () => Promise<Returned>;\n};\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal;\n}\ntype AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg,\n// any handling\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// unknown handling\nunknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n: [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n: [void] extends [ThunkArg] // make optional\n? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n: [undefined] extends [ThunkArg] ? WithStrictNullChecks<\n// with strict nullChecks: make optional\n(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// without strict null checks this will match everything, so don't make it optional\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> // default case: normal argument\n: (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean;\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string;\n} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   *\n   * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n   * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n   */\n  getPendingMeta?(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   */\n  getPendingMeta(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}>;\nexport type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?], undefined, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'pending';\n} & GetPendingMeta<ThunkApiConfig>>;\nexport type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Error | null, string, ThunkArg, GetRejectValue<ThunkApiConfig>?, GetRejectedMeta<ThunkApiConfig>?], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'rejected';\n  aborted: boolean;\n  condition: boolean;\n} & (({\n  rejectedWithValue: false;\n} & { [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined }) | ({\n  rejectedWithValue: true;\n} & GetRejectedMeta<ThunkApiConfig>))>;\nexport type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?], Returned, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'fulfilled';\n} & GetFulfilledMeta<ThunkApiConfig>>;\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;\n  fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;\n  // matchSettled?\n  settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;\n  typePrefix: string;\n};\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;\nexport type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n  withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\nconst externalAbortMessage = 'External signal was aborted';\nexport const createAsyncThunk = /* @__PURE__ */(() => {\n  function createAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>;\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>;\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>;\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>;\n    const fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/fulfilled', (payload: Returned, requestId: string, arg: ThunkArg, meta?: FulfilledMeta) => ({\n      payload,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'fulfilled' as const\n      }\n    }));\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/pending', (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n      payload: undefined,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'pending' as const\n      }\n    }));\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/rejected', (error: Error | null, requestId: string, arg: ThunkArg, payload?: RejectedValue, meta?: RejectedMeta) => ({\n      payload,\n      error: (options && options.serializeError || miniSerializeError)(error || 'Rejected') as GetSerializedErrorType<ThunkApiConfig>,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        rejectedWithValue: !!payload,\n        requestStatus: 'rejected' as const,\n        aborted: error?.name === 'AbortError',\n        condition: error?.name === 'ConditionError'\n      }\n    }));\n    function actionCreator(arg: ThunkArg, {\n      signal\n    }: AsyncThunkDispatchConfig = {}): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n        const abortController = new AbortController();\n        let abortHandler: (() => void) | undefined;\n        let abortReason: string | undefined;\n        function abort(reason?: string) {\n          abortReason = reason;\n          abortController.abort();\n        }\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage);\n          } else {\n            signal.addEventListener('abort', () => abort(externalAbortMessage), {\n              once: true\n            });\n          }\n        }\n        const promise = async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>;\n          try {\n            let conditionResult = options?.condition?.(arg, {\n              getState,\n              extra\n            });\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult;\n            }\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.'\n              };\n            }\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted'\n                });\n              };\n              abortController.signal.addEventListener('abort', abortHandler, {\n                once: true\n              });\n            });\n            dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n              requestId,\n              arg\n            }, {\n              getState,\n              extra\n            })) as any);\n            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n              dispatch,\n              getState,\n              extra,\n              requestId,\n              signal: abortController.signal,\n              abort,\n              rejectWithValue: ((value: RejectedValue, meta?: RejectedMeta) => {\n                return new RejectWithValue(value, meta);\n              }) as any,\n              fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                return new FulfillWithMeta(value, meta);\n              }) as any\n            })).then(result => {\n              if (result instanceof RejectWithValue) {\n                throw result;\n              }\n              if (result instanceof FulfillWithMeta) {\n                return fulfilled(result.payload, requestId, arg, result.meta);\n              }\n              return fulfilled(result as any, requestId, arg);\n            })]);\n          } catch (err) {\n            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err as any, requestId, arg);\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler);\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && (finalAction as any).meta.condition;\n          if (!skipDispatch) {\n            dispatch(finalAction as any);\n          }\n          return finalAction;\n        }();\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult);\n          }\n        });\n      };\n    }\n    return Object.assign(actionCreator as AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig>, {\n      pending,\n      rejected,\n      fulfilled,\n      settled: isAnyOf(rejected, fulfilled),\n      typePrefix\n    });\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk;\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>;\n})();\ninterface UnwrappableAction {\n  payload: any;\n  meta?: any;\n  error?: any;\n}\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {\n  error: any;\n}>['payload'];\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload;\n  }\n  if (action.error) {\n    throw action.error;\n  }\n  return action.payload;\n}\ntype WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return value !== null && typeof value === 'object' && typeof value.then === 'function';\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { Selector } from 'reselect';\nimport type { InjectConfig } from './combineSlices';\nimport type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport type { AsyncThunk, AsyncThunkConfig, AsyncThunkOptions, AsyncThunkPayloadCreator, OverrideThunkApiConfigs } from './createAsyncThunk';\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk';\nimport type { ActionMatcherDescriptionCollection, CaseReducer, ReducerWithInitialState } from './createReducer';\nimport { createReducer } from './createReducer';\nimport type { ActionReducerMapBuilder, AsyncThunkReducers, TypedActionCreator } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { Id, TypeGuard } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\nconst asyncThunkSymbol = /* @__PURE__ */Symbol.for('rtk-slice-createasyncthunk');\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk;\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk\n};\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath;\n};\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice name.\n   */\n  name: Name;\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath;\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>;\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>;\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>;\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State;\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>>;\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {\n    inject: (slice: {\n      reducerPath: string;\n      reducer: Reducer;\n    }, config?: InjectConfig) => void;\n  }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State;\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]?: State | undefined }>>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State;\n};\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name;\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath;\n\n  /**\n   * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n   */\n  initialState: State | (() => State);\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n  ```ts\n  import { createAction, createSlice, Action } from '@reduxjs/toolkit'\n  const incrementBy = createAction<number>('incrementBy')\n  const decrement = createAction('decrement')\n  interface RejectedAction extends Action {\n  error: Error\n  }\n  function isRejectedAction(action: Action): action is RejectedAction {\n  return action.type.endsWith('rejected')\n  }\n  createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {},\n  extraReducers: builder => {\n    builder\n      .addCase(incrementBy, (state, action) => {\n        // action is inferred correctly here if using TS\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {})\n      // You can match a range of action types\n      .addMatcher(\n        isRejectedAction,\n        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n        (state, action) => {}\n      )\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {})\n    }\n  })\n  ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors;\n}\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T;\n};\nexport type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>;\n  prepare: PrepareAction<Action['payload']>;\n};\nexport interface CaseReducerWithPrepareDefinition<State, Action extends PayloadAction> extends CaseReducerWithPrepare<State, Action>, ReducerDefinition<ReducerType.reducerWithPrepare> {}\ntype AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;\n};\ntype AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;\n};\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = { [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K] };\ninterface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {\n  <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;\n  <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;\n  withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n}\nexport interface ReducerCreators<State> {\n  reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;\n  reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;\n  asyncThunk: AsyncThunkCreator<State>;\n  preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare;\n    prepare: Prepare;\n    reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;\n  };\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any;\n};\ntype SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {\n  prepare: any;\n} ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {\n  reducer: any;\n} ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never };\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<CR extends {\n  prepare: any;\n}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ((state: any, action: infer Action) => any) ? Action extends {\n  payload: infer P;\n} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {\n  reducer: infer Reducer;\n} ? Reducer : Definition : never };\ntype RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {\n  unwrapped: S;\n} : never;\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState> };\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends {\n  reducer(s: S, action?: infer A): any;\n} ? {\n  prepare(...a: never[]): Omit<A, 'type'>;\n} : {} };\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`;\n}\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator;\n  };\n}\nexport function buildCreateSlice({\n  creators\n}: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n  return function createSlice<State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {\n    const {\n      name,\n      reducerPath = name as unknown as ReducerPath\n    } = options;\n    if (!name) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(11) : '`name` is a required option for createSlice');\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (options.initialState === undefined) {\n        console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`');\n      }\n    }\n    const reducers = (typeof options.reducers === 'function' ? options.reducers(buildReducerCreators<State>()) : options.reducers) || {};\n    const reducerNames = Object.keys(reducers);\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: []\n    };\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<State>) {\n        const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n        if (!type) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(12) : '`context.addCase` cannot be called with an empty action type');\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(13) : '`context.addCase` cannot be called with two reducers for the same action type: ' + type);\n        }\n        context.sliceCaseReducersByType[type] = reducer;\n        return contextMethods;\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({\n          matcher,\n          reducer\n        });\n        return contextMethods;\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator;\n        return contextMethods;\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer;\n        return contextMethods;\n      }\n    };\n    reducerNames.forEach(reducerName => {\n      const reducerDefinition = reducers[reducerName];\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function'\n      };\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n      } else {\n        handleNormalReducerDefinition<State>(reducerDetails, reducerDefinition as any, contextMethods);\n      }\n    });\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n        }\n      }\n      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = undefined] = typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType\n      };\n      return createReducer(options.initialState, builder => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>);\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer);\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer);\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer);\n        }\n      });\n    }\n    const selectSelf = (state: State) => state;\n    const injectedSelectorCache = new Map<boolean, WeakMap<(rootState: any) => State | undefined, Record<string, (rootState: any) => any>>>();\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>();\n    let _reducer: ReducerWithInitialState<State>;\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer(state, action);\n    }\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer.getInitialState();\n    }\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(reducerPath: CurrentReducerPath, injected = false): Pick<Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'> {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath];\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(15) : 'selectSlice returned undefined for an uninjected slice reducer');\n          }\n        }\n        return sliceState;\n      }\n      function getSelectors(selectState: (rootState: any) => State = selectSelf) {\n        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => new WeakMap());\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {};\n          for (const [name, selector] of Object.entries(options.selectors ?? {})) {\n            map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);\n          }\n          return map;\n        }) as any;\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice);\n        },\n        selectSlice\n      };\n    }\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, {\n        reducerPath: pathOpt,\n        ...config\n      } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath;\n        injectable.inject({\n          reducerPath: newReducerPath,\n          reducer\n        }, config);\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true)\n        } as any;\n      }\n    };\n    return slice;\n  };\n}\nfunction wrapSelector<State, NewState, S extends Selector<State>>(selector: S, selectState: Selector<NewState, State>, getInitialState: () => State, injected?: boolean) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState);\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState();\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(16) : 'selectState returned undefined for an uninjected slice reducer');\n      }\n    }\n    return selector(sliceState, ...args);\n  }\n  wrapper.unwrapped = selector;\n  return wrapper as RemappedSelector<S, NewState>;\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */buildCreateSlice();\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<string, CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>>;\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>;\n  sliceMatchers: ActionMatcherDescriptionCollection<State>;\n  actionCreators: Record<string, Function>;\n}\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ReducerHandlingContextMethods<State>;\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ReducerHandlingContextMethods<State>;\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<State, A extends Action ? A : A & Action>): ReducerHandlingContextMethods<State>;\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * context.exposeAction(\"addPost\", createAction<Post>(\"addPost\"));\n   *\n   * export const { addPost } = slice.actions\n   *\n   * dispatch(addPost(post))\n   */\n  exposeAction(name: string, actionCreator: Function): ReducerHandlingContextMethods<State>;\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * context.exposeCaseReducer(\"addPost\", (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload)\n   * })\n   *\n   * slice.caseReducers.addPost([], addPost(post))\n   */\n  exposeCaseReducer(name: string, reducer: CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>): ReducerHandlingContextMethods<State>;\n}\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string;\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string;\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean;\n}\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(payloadCreator: AsyncThunkPayloadCreator<any, any>, config: AsyncThunkSliceReducerConfig<State, any>): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config\n    };\n  }\n  asyncThunk.withTypes = () => asyncThunk;\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign({\n        // hack so the wrapping function has the same name as the original\n        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n        [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n          return caseReducer(...args);\n        }\n      }[caseReducer.name], {\n        _reducerDefinitionType: ReducerType.reducer\n      } as const);\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer\n      };\n    },\n    asyncThunk: asyncThunk as any\n  };\n}\nfunction handleNormalReducerDefinition<State>({\n  type,\n  reducerName,\n  createNotation\n}: ReducerDetails, maybeReducerWithPrepare: CaseReducer<State, {\n  payload: any;\n  type: string;\n}> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, context: ReducerHandlingContextMethods<State>) {\n  let caseReducer: CaseReducer<State, any>;\n  let prepareCallback: PrepareAction<any> | undefined;\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(17) : 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.');\n    }\n    caseReducer = maybeReducerWithPrepare.reducer;\n    prepareCallback = maybeReducerWithPrepare.prepare;\n  } else {\n    caseReducer = maybeReducerWithPrepare;\n  }\n  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition<State>(reducerDefinition: any): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk;\n}\nfunction isCaseReducerWithPrepareDefinition<State>(reducerDefinition: any): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare;\n}\nfunction handleThunkCaseReducerDefinition<State>({\n  type,\n  reducerName\n}: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, context: ReducerHandlingContextMethods<State>, cAT: typeof _createAsyncThunk | undefined) {\n  if (!cAT) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(18) : 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.');\n  }\n  const {\n    payloadCreator,\n    fulfilled,\n    pending,\n    rejected,\n    settled,\n    options\n  } = reducerDefinition;\n  const thunk = cAT(type, payloadCreator, options as any);\n  context.exposeAction(reducerName, thunk);\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled);\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending);\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected);\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled);\n  }\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop\n  });\n}\nfunction noop() {}","import type { EntityId, EntityState, EntityStateAdapter, EntityStateFactory } from './models';\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<T, Id> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>\n  };\n}\nexport function createInitialStateFactory<T, Id extends EntityId>(stateAdapter: EntityStateAdapter<T, Id>): EntityStateFactory<T, Id> {\n  function getInitialState(state?: undefined, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id>;\n  function getInitialState<S extends object>(additionalState: S, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id> & S;\n  function getInitialState(additionalState: any = {}, entities?: readonly T[] | Record<Id, T>): any {\n    const state = Object.assign(getInitialEntityState(), additionalState);\n    return entities ? stateAdapter.setAll(state, entities) : state;\n  }\n  return {\n    getInitialState\n  };\n}","import type { CreateSelectorFunction, Selector } from 'reselect';\nimport { createDraftSafeSelector } from '../createDraftSafeSelector';\nimport type { EntityId, EntitySelectors, EntityState } from './models';\ntype AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction;\n};\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;\n  function getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;\n  function getSelectors<V>(selectState?: (state: V) => EntityState<T, Id>, options: GetSelectorsOptions = {}): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction\n    } = options;\n    const selectIds = (state: EntityState<T, Id>) => state.ids;\n    const selectEntities = (state: EntityState<T, Id>) => state.entities;\n    const selectAll = createSelector(selectIds, selectEntities, (ids, entities): T[] => ids.map(id => entities[id]!));\n    const selectId = (_: unknown, id: Id) => id;\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id];\n    const selectTotal = createSelector(selectIds, ids => ids.length);\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById)\n      };\n    }\n    const selectGlobalizedEntities = createSelector(selectState as Selector<V, EntityState<T, Id>>, selectEntities);\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(selectGlobalizedEntities, selectId, selectById)\n    };\n  }\n  return {\n    getSelectors\n  };\n}","import { createNextState, isDraft } from '../immerImports';\nimport type { Draft } from 'immer';\nimport type { EntityId, DraftableEntityState, PreventAny } from './models';\nimport type { PayloadAction } from '../createAction';\nimport { isFSA } from '../createAction';\nexport const isDraftTyped = isDraft as <T>(value: T | Draft<T>) => value is Draft<T>;\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(mutator: (state: DraftableEntityState<T, Id>) => void) {\n  const operator = createStateOperator((_: undefined, state: DraftableEntityState<T, Id>) => mutator(state));\n  return function operation<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S {\n    return operator(state as S, undefined);\n  };\n}\nexport function createStateOperator<T, Id extends EntityId, R>(mutator: (arg: R, state: DraftableEntityState<T, Id>) => void) {\n  return function operation<S extends DraftableEntityState<T, Id>>(state: S, arg: R | PayloadAction<R>): S {\n    function isPayloadActionArgument(arg: R | PayloadAction<R>): arg is PayloadAction<R> {\n      return isFSA(arg);\n    }\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft);\n      } else {\n        mutator(arg, draft);\n      }\n    };\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state);\n\n      // since it's a draft, we'll just return it\n      return state;\n    }\n    return createNextState(state, runMutator);\n  };\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../immerImports';\nimport type { DraftableEntityState, EntityId, IdSelector, Update } from './models';\nexport function selectIdValue<T, Id extends EntityId>(entity: T, selectId: IdSelector<T, Id>) {\n  const key = selectId(entity);\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    console.warn('The entity passed to the `selectId` implementation returned undefined.', 'You should probably provide your own `selectId` implementation.', 'The entity that was passed:', entity, 'The `selectId` implementation:', selectId.toString());\n  }\n  return key;\n}\nexport function ensureEntitiesArray<T, Id extends EntityId>(entities: readonly T[] | Record<Id, T>): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities);\n  }\n  return entities;\n}\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}\nexport function splitAddedUpdatedEntities<T, Id extends EntityId>(newEntities: readonly T[] | Record<Id, T>, selectId: IdSelector<T, Id>, state: DraftableEntityState<T, Id>): [T[], Update<T, Id>[], Id[]] {\n  newEntities = ensureEntitiesArray(newEntities);\n  const existingIdsArray = getCurrent(state.ids);\n  const existingIds = new Set<Id>(existingIdsArray);\n  const added: T[] = [];\n  const addedIds = new Set<Id>([]);\n  const updated: Update<T, Id>[] = [];\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId);\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({\n        id,\n        changes: entity\n      });\n    } else {\n      addedIds.add(id);\n      added.push(entity);\n    }\n  }\n  return [added, updated, existingIdsArray];\n}","import type { Draft } from 'immer';\nimport type { EntityStateAdapter, IdSelector, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator, createSingleArgumentStateOperator } from './state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities } from './utils';\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (key in state.entities) {\n      return;\n    }\n    state.ids.push(key as Id & Draft<Id>);\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      addOneMutably(entity, state);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>);\n    }\n    ;\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      setOneMutably(entity, state);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.ids = [];\n    state.entities = {} as Record<Id, T>;\n    addManyMutably(newEntities, state);\n  }\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state);\n  }\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false;\n    keys.forEach(key => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key];\n        didMutate = true;\n      }\n    });\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter(id => id in state.entities) as Id[] | Draft<Id[]>;\n    }\n  }\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {}\n    });\n  }\n  function takeNewKey(keys: {\n    [id: string]: Id;\n  }, update: Update<T, Id>, state: R): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id];\n    if (original === undefined) {\n      return false;\n    }\n    const updated: T = Object.assign({}, original, update.changes);\n    const newKey = selectIdValue(updated, selectId);\n    const hasNewKey = newKey !== update.id;\n    if (hasNewKey) {\n      keys[update.id] = newKey;\n      delete (state.entities as Record<Id, T>)[update.id];\n    }\n    ;\n    (state.entities as Record<Id, T>)[newKey] = updated;\n    return hasNewKey;\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    const newKeys: {\n      [id: string]: Id;\n    } = {};\n    const updatesPerEntity: {\n      [id: string]: Update<T, Id>;\n    } = {};\n    updates.forEach(update => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes\n          }\n        };\n      }\n    });\n    updates = Object.values(updatesPerEntity);\n    const didMutateEntities = updates.length > 0;\n    if (didMutateEntities) {\n      const didMutateIds = updates.filter(update => takeNewKey(newKeys, update, state)).length > 0;\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map(e => selectIdValue(e as T, selectId));\n      }\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    addManyMutably(added, state);\n    updateManyMutably(updated, state);\n  }\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably)\n  };\n}","import type { IdSelector, Comparer, EntityStateAdapter, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator } from './state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities, getCurrent } from './utils';\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): number {\n  let lowIndex = 0;\n  let highIndex = sortedItems.length;\n  while (lowIndex < highIndex) {\n    let middleIndex = lowIndex + highIndex >>> 1;\n    const currentItem = sortedItems[middleIndex];\n    const res = comparisonFunction(item, currentItem);\n    if (res >= 0) {\n      lowIndex = middleIndex + 1;\n    } else {\n      highIndex = middleIndex;\n    }\n  }\n  return lowIndex;\n}\nexport function insert<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n  sortedItems.splice(insertAtIndex, 0, item);\n  return sortedItems;\n}\nexport function createSortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>, comparer: Comparer<T>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  const {\n    removeOne,\n    removeMany,\n    removeAll\n  } = createUnsortedStateAdapter(selectId);\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state);\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R, existingIds?: Id[]): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids));\n    const addedKeys = new Set<Id>();\n    const models = newEntities.filter(model => {\n      const modelId = selectIdValue(model, selectId);\n      const notAdded = !addedKeys.has(modelId);\n      if (notAdded) addedKeys.add(modelId);\n      return !existingKeys.has(modelId) && notAdded;\n    });\n    if (models.length !== 0) {\n      mergeFunction(state, models);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state);\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    let deduplicatedEntities = {} as Record<Id, T>;\n    newEntities = ensureEntitiesArray(newEntities);\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        const entityId = selectId(item);\n        // For multiple items with the same ID, we should keep the last one.\n        deduplicatedEntities[entityId] = item;\n        delete (state.entities as Record<Id, T>)[entityId];\n      }\n      newEntities = ensureEntitiesArray(deduplicatedEntities);\n      mergeFunction(state, newEntities);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.entities = {} as Record<Id, T>;\n    state.ids = [];\n    addManyMutably(newEntities, state, []);\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    let appliedUpdates = false;\n    let replacedIds = false;\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id];\n      if (!entity) {\n        continue;\n      }\n      appliedUpdates = true;\n      Object.assign(entity, update.changes);\n      const newId = selectId(entity);\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true;\n        delete (state.entities as Record<Id, T>)[update.id];\n        const oldIndex = (state.ids as Id[]).indexOf(update.id);\n        state.ids[oldIndex] = newId;\n        (state.entities as Record<Id, T>)[newId] = entity;\n      }\n    }\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds);\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray);\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state);\n    }\n  }\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue;\n      }\n      return false;\n    }\n    return true;\n  }\n  type MergeFunction = (state: R, addedItems: readonly T[], appliedUpdates?: boolean, replacedIds?: boolean) => void;\n  const mergeFunction: MergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n    const currentEntities = getCurrent(state.entities);\n    const currentIds = getCurrent(state.ids);\n    const stateEntities = state.entities as Record<Id, T>;\n    let ids: Iterable<Id> = currentIds;\n    if (replacedIds) {\n      ids = new Set(currentIds);\n    }\n    let sortedEntities: T[] = [];\n    for (const id of ids) {\n      const entity = currentEntities[id];\n      if (entity) {\n        sortedEntities.push(entity);\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0;\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item;\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer);\n      }\n    }\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer);\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer);\n    }\n    const newSortedIds = sortedEntities.map(selectId);\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds;\n    }\n  };\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably)\n  };\n}","import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models';\nimport { createInitialStateFactory } from './entity_state';\nimport { createSelectorsFactory } from './state_selectors';\nimport { createSortedStateAdapter } from './sorted_state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport type { WithRequiredProp } from '../tsHelpers';\nexport function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;\nexport function createEntityAdapter<T extends {\n  id: EntityId;\n}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(options: EntityAdapterOptions<T, EntityId> = {}): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options\n  };\n  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n  const stateFactory = createInitialStateFactory(stateAdapter);\n  const selectorsFactory = createSelectorsFactory<T, EntityId>();\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter\n  };\n}","import type { SerializedError } from '@reduxjs/toolkit';\nconst task = 'task';\nconst listener = 'listener';\nconst completed = 'completed';\nconst cancelled = 'cancelled';\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const;\nexport const taskCompleted = `task-${completed}` as const;\nexport const listenerCancelled = `${listener}-${cancelled}` as const;\nexport const listenerCompleted = `${listener}-${completed}` as const;\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError';\n  message: string;\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nexport const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown = (func: unknown, expected: string) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(32) : `${expected} is not a function`);\n  }\n};\nexport const noop = () => {};\nexport const catchRejection = <T,>(promise: Promise<T>, onError = noop): Promise<T> => {\n  promise.catch(onError);\n  return promise;\n};\nexport const addAbortSignalListener = (abortSignal: AbortSignal, callback: (evt: Event) => void) => {\n  abortSignal.addEventListener('abort', callback, {\n    once: true\n  });\n  return () => abortSignal.removeEventListener('abort', callback);\n};","import { TaskAbortError } from './exceptions';\nimport type { TaskResult } from './types';\nimport { addAbortSignalListener, catchRejection, noop } from './utils';\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @see {TaskAbortError}\n * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    throw new TaskAbortError(signal.reason);\n  }\n};\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(signal: AbortSignal, promise: Promise<T>): Promise<T> {\n  let cleanup = noop;\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n    if (signal.aborted) {\n      notifyRejection();\n      return;\n    }\n    cleanup = addAbortSignalListener(signal, notifyRejection);\n    promise.finally(() => cleanup()).then(resolve, reject);\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop;\n  });\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T,>(task: () => Promise<T>, cleanUp?: () => void): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve();\n    const value = await task();\n    return {\n      status: 'ok',\n      value\n    };\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error\n    };\n  } finally {\n    cleanUp?.();\n  }\n};\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T,>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(raceWithSignal(signal, promise).then(output => {\n      validateActive(signal);\n      return output;\n    }));\n  };\n};\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal);\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>(resolve => setTimeout(resolve, timeoutMs)));\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux';\nimport { isAction } from '../reduxImports';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport { createAction } from '../createAction';\nimport { nanoid } from '../nanoid';\nimport { TaskAbortError, listenerCancelled, listenerCompleted, taskCancelled, taskCompleted } from './exceptions';\nimport { createDelay, createPause, raceWithSignal, runTask, validateActive } from './task';\nimport type { AddListenerOverloads, AnyListenerPredicate, CreateListenerMiddlewareOptions, FallbackAddListenerOptions, ForkOptions, ForkedTask, ForkedTaskExecutor, ListenerEntry, ListenerErrorHandler, ListenerErrorInfo, ListenerMiddleware, ListenerMiddlewareInstance, TakePattern, TaskResult, TypedAddListener, TypedCreateListenerEntry, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\nimport { addAbortSignalListener, assertFunction, catchRejection, noop } from './utils';\nexport { TaskAbortError } from './exceptions';\nexport type { AsyncTaskExecutor, CreateListenerMiddlewareOptions, ForkedTask, ForkedTaskAPI, ForkedTaskExecutor, ListenerEffect, ListenerEffectAPI, ListenerErrorHandler, ListenerMiddleware, ListenerMiddlewareInstance, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, TypedAddListener, TypedRemoveListener, TypedStartListening, TypedStopListening, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\n\n//Overly-aggressive byte-shaving\nconst {\n  assign\n} = Object;\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const;\nconst alm = 'listenerMiddleware' as const;\nconst createFork = (parentAbortSignal: AbortSignal, parentBlockingPromises: Promise<any>[]) => {\n  const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));\n  return <T,>(taskExecutor: ForkedTaskExecutor<T>, opts?: ForkOptions): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor');\n    const childAbortController = new AbortController();\n    linkControllers(childAbortController);\n    const result = runTask<T>(async (): Promise<T> => {\n      validateActive(parentAbortSignal);\n      validateActive(childAbortController.signal);\n      const result = (await taskExecutor({\n        pause: createPause(childAbortController.signal),\n        delay: createDelay(childAbortController.signal),\n        signal: childAbortController.signal\n      })) as T;\n      validateActive(childAbortController.signal);\n      return result;\n    }, () => childAbortController.abort(taskCompleted));\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop));\n    }\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        childAbortController.abort(taskCancelled);\n      }\n    };\n  };\n};\nconst createTakePattern = <S,>(startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>, signal: AbortSignal): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>,>(predicate: P, timeout: number | undefined) => {\n    validateActive(signal);\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {};\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe();\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n        }\n      });\n      unsubscribe = () => {\n        stopListening();\n        reject();\n      };\n    });\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise];\n    if (timeout != null) {\n      promises.push(new Promise<null>(resolve => setTimeout(resolve, timeout, null)));\n    }\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises));\n      validateActive(signal);\n      return output;\n    } finally {\n      // Always clean up the listener\n      unsubscribe();\n    }\n  };\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) => catchRejection(take(predicate, timeout))) as TakePattern<S>;\n};\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let {\n    type,\n    actionCreator,\n    matcher,\n    predicate,\n    effect\n  } = options;\n  if (type) {\n    predicate = createAction(type).match;\n  } else if (actionCreator) {\n    type = actionCreator!.type;\n    predicate = actionCreator.match;\n  } else if (matcher) {\n    predicate = matcher;\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(21) : 'Creating or removing a listener requires one of the known fields for matching an action');\n  }\n  assertFunction(effect, 'options.listener');\n  return {\n    predicate,\n    type,\n    effect\n  };\n};\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> = /* @__PURE__ */assign((options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    predicate,\n    effect\n  } = getListenerEntryPropsFrom(options);\n  const entry: ListenerEntry<unknown> = {\n    id: nanoid(),\n    effect,\n    type,\n    predicate,\n    pending: new Set<AbortController>(),\n    unsubscribe: () => {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(22) : 'Unsubscribe not initialized');\n    }\n  };\n  return entry;\n}, {\n  withTypes: () => createListenerEntry\n}) as unknown as TypedCreateListenerEntry<unknown>;\nconst findListenerEntry = (listenerMap: Map<string, ListenerEntry>, options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    effect,\n    predicate\n  } = getListenerEntryPropsFrom(options);\n  return Array.from(listenerMap.values()).find(entry => {\n    const matchPredicateOrType = typeof type === 'string' ? entry.type === type : entry.predicate === predicate;\n    return matchPredicateOrType && entry.effect === effect;\n  });\n};\nconst cancelActiveListeners = (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>) => {\n  entry.pending.forEach(controller => {\n    controller.abort(listenerCancelled);\n  });\n};\nconst createClearListenerMiddleware = (listenerMap: Map<string, ListenerEntry>, executingListeners: Map<ListenerEntry, number>) => {\n  return () => {\n    for (const listener of executingListeners.keys()) {\n      cancelActiveListeners(listener);\n    }\n    listenerMap.clear();\n  };\n};\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (errorHandler: ListenerErrorHandler, errorToNotify: unknown, errorInfo: ListenerErrorInfo): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo);\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError;\n    }, 0);\n  }\n};\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/add`), {\n  withTypes: () => addListener\n}) as unknown as TypedAddListener<unknown>;\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */createAction(`${alm}/removeAll`);\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/remove`), {\n  withTypes: () => removeListener\n}) as unknown as TypedRemoveListener<unknown>;\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args);\n};\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {}) => {\n  const listenerMap = new Map<string, ListenerEntry>();\n\n  // Track listeners whose effect is currently executing so clearListeners can\n  // abort even listeners that have become unsubscribed while executing.\n  const executingListeners = new Map<ListenerEntry, number>();\n  const trackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 0;\n    executingListeners.set(entry, count + 1);\n  };\n  const untrackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 1;\n    if (count === 1) {\n      executingListeners.delete(entry);\n    } else {\n      executingListeners.set(entry, count - 1);\n    }\n  };\n  const {\n    extra,\n    onError = defaultErrorHandler\n  } = middlewareOptions;\n  assertFunction(onError, 'onError');\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id);\n    listenerMap.set(entry.id, entry);\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe();\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    };\n  };\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options as any);\n    return insertEntry(entry);\n  }) as AddListenerOverloads<any>;\n  assign(startListening, {\n    withTypes: () => startListening\n  });\n  const stopListening = (options: FallbackAddListenerOptions & UnsubscribeListenerOptions): boolean => {\n    const entry = findListenerEntry(listenerMap, options);\n    if (entry) {\n      entry.unsubscribe();\n      if (options.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    }\n    return !!entry;\n  };\n  assign(stopListening, {\n    withTypes: () => stopListening\n  });\n  const notifyListener = async (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>, action: unknown, api: MiddlewareAPI, getOriginalState: () => StateType) => {\n    const internalTaskController = new AbortController();\n    const take = createTakePattern(startListening as AddListenerOverloads<any>, internalTaskController.signal);\n    const autoJoinPromises: Promise<any>[] = [];\n    try {\n      entry.pending.add(internalTaskController);\n      trackExecutingListener(entry);\n      await Promise.resolve(entry.effect(action,\n      // Use assign() rather than ... to avoid extra helper functions added to bundle\n      assign({}, api, {\n        getOriginalState,\n        condition: (predicate: AnyListenerPredicate<any>, timeout?: number) => take(predicate, timeout).then(Boolean),\n        take,\n        delay: createDelay(internalTaskController.signal),\n        pause: createPause<any>(internalTaskController.signal),\n        extra,\n        signal: internalTaskController.signal,\n        fork: createFork(internalTaskController.signal, autoJoinPromises),\n        unsubscribe: entry.unsubscribe,\n        subscribe: () => {\n          listenerMap.set(entry.id, entry);\n        },\n        cancelActiveListeners: () => {\n          entry.pending.forEach((controller, _, set) => {\n            if (controller !== internalTaskController) {\n              controller.abort(listenerCancelled);\n              set.delete(controller);\n            }\n          });\n        },\n        cancel: () => {\n          internalTaskController.abort(listenerCancelled);\n          entry.pending.delete(internalTaskController);\n        },\n        throwIfCancelled: () => {\n          validateActive(internalTaskController.signal);\n        }\n      })));\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect'\n        });\n      }\n    } finally {\n      await Promise.all(autoJoinPromises);\n      internalTaskController.abort(listenerCompleted); // Notify that the task has completed\n      untrackExecutingListener(entry);\n      entry.pending.delete(internalTaskController);\n    }\n  };\n  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);\n  const middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument> = api => next => action => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action);\n    }\n    if (addListener.match(action)) {\n      return startListening(action.payload as any);\n    }\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware();\n      return;\n    }\n    if (removeListener.match(action)) {\n      return stopListening(action.payload);\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState();\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);\n      }\n      return originalState as StateType;\n    };\n    let result: unknown;\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action);\n      if (listenerMap.size > 0) {\n        const currentState = api.getState();\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values());\n        for (const entry of listenerEntries) {\n          let runListener = false;\n          try {\n            runListener = entry.predicate(action, currentState, originalState);\n          } catch (predicateError) {\n            runListener = false;\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate'\n            });\n          }\n          if (!runListener) {\n            continue;\n          }\n          notifyListener(entry, action, api, getOriginalState);\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN;\n    }\n    return result;\n  };\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;\n};","import type { Dispatch, Middleware, UnknownAction } from 'redux';\nimport { compose } from '../reduxImports';\nimport { createAction } from '../createAction';\nimport { isAllOf } from '../matchers';\nimport { nanoid } from '../nanoid';\nimport { getOrInsertComputed } from '../utils';\nimport type { AddMiddleware, DynamicMiddleware, DynamicMiddlewareInstance, MiddlewareEntry, WithMiddleware } from './types';\nexport type { DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './types';\nconst createMiddlewareEntry = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(middleware: Middleware<any, State, DispatchType>): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map()\n});\nconst matchInstance = (instanceId: string) => (action: any): action is {\n  meta: {\n    instanceId: string;\n  };\n} => action?.meta?.instanceId === instanceId;\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid();\n  const middlewareMap = new Map<Middleware<any, State, DispatchType>, MiddlewareEntry<State, DispatchType>>();\n  const withMiddleware = Object.assign(createAction('dynamicMiddleware/add', (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n    payload: middlewares,\n    meta: {\n      instanceId\n    }\n  })), {\n    withTypes: () => withMiddleware\n  }) as WithMiddleware<State, DispatchType>;\n  const addMiddleware = Object.assign(function addMiddleware(...middlewares: Middleware<any, State, DispatchType>[]) {\n    middlewares.forEach(middleware => {\n      getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);\n    });\n  }, {\n    withTypes: () => addMiddleware\n  }) as AddMiddleware<State, DispatchType>;\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = api => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map(entry => getOrInsertComputed(entry.applied, api, entry.middleware));\n    return compose(...appliedMiddleware);\n  };\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n  const middleware: DynamicMiddleware<State, DispatchType> = api => next => action => {\n    if (isWithMiddleware(action)) {\n      addMiddleware(...action.payload);\n      return api.dispatch;\n    }\n    return getFinalMiddleware(api)(next)(action);\n  };\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { PreloadedStateShapeFromReducersMapObject, Reducer, StateFromReducersMapObject, UnknownAction } from 'redux';\nimport { combineReducers } from 'redux';\nimport { nanoid } from './nanoid';\nimport type { Id, NonUndefined, Tail, UnionToIntersection, WithOptionalProp } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\ntype SliceLike<ReducerPath extends string, State, PreloadedState = State> = {\n  reducerPath: ReducerPath;\n  reducer: Reducer<State, any, PreloadedState>;\n};\ntype AnySliceLike = SliceLike<string, any>;\ntype SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;\ntype SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;\ntype SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;\nexport type WithSlice<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikeState<A> };\nexport type WithSlicePreloadedState<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A> };\ntype ReducerMap = Record<string, Reducer>;\ntype ExistingSliceLike<DeclaredState, PreloadedState> = { [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>> }[keyof DeclaredState];\nexport type InjectConfig = {\n  /**\n   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.\n   */\n  overrideExisting?: boolean;\n};\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;\n  };\n}\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;\ntype InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;\nconst isSliceLike = (maybeSliceLike: AnySliceLike | ReducerMap): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string';\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) => slices.flatMap<[string, Reducer]>(sliceOrMap => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original');\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE];\nconst stateProxyMap = new WeakMap<object, object>();\nconst createStateProxy = <State extends object,>(state: State, reducerMap: Partial<Record<PropertyKey, Reducer>>, initialStateCache: Record<PropertyKey, unknown>) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {\n  get: (target, prop, receiver) => {\n    if (prop === ORIGINAL_STATE) return target;\n    const result = Reflect.get(target, prop, receiver);\n    if (typeof result === 'undefined') {\n      const cached = initialStateCache[prop];\n      if (typeof cached !== 'undefined') return cached;\n      const reducer = reducerMap[prop];\n      if (reducer) {\n        // ensure action type is random, to prevent reducer treating it differently\n        const reducerResult = reducer(undefined, {\n          type: nanoid()\n        });\n        if (typeof reducerResult === 'undefined') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). ` + `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + `you can use null instead of undefined.`);\n        }\n        initialStateCache[prop] = reducerResult;\n        return reducerResult;\n      }\n    }\n    return result;\n  }\n})) as State;\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(25) : 'original must be used on state Proxy');\n  }\n  return state[ORIGINAL_STATE];\n};\nconst emptyObject = {};\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state;\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>> {\n  const reducerMap = Object.fromEntries(getReducers(slices));\n  const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;\n  let reducer = getReducer();\n  function combinedReducer(state: Record<string, unknown>, action: UnknownAction) {\n    return reducer(state, action);\n  }\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n  const initialStateCache: Record<PropertyKey, unknown> = {};\n  const inject = (slice: AnySliceLike, config: InjectConfig = {}): typeof combinedReducer => {\n    const {\n      reducerPath,\n      reducer: reducerToInject\n    } = slice;\n    const currentReducer = reducerMap[reducerPath];\n    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n      }\n      return combinedReducer;\n    }\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath];\n    }\n    reducerMap[reducerPath] = reducerToInject;\n    reducer = getReducer();\n    return combinedReducer;\n  };\n  const selector = Object.assign(function makeSelector<State extends object, RootState, Args extends any[]>(selectorFn: (state: State, ...args: Args) => any, selectState?: (rootState: RootState, ...args: Args) => State) {\n    return function selector(state: State, ...args: Args) {\n      return selectorFn(createStateProxy(selectState ? selectState(state as any, ...args) : state, reducerMap, initialStateCache), ...args);\n    };\n  }, {\n    original\n  });\n  return Object.assign(combinedReducer, {\n    inject,\n    selector\n  }) as any;\n}","/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` + 'use the non-minified dev environment for full errors. ';\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAAA,IACtI;AAAA,EACF,GAAG;AAAA,IACD;AAAA,EACF,CAAC;AACD,SAAO,OAAO,OAAO,iBAAiB;AAAA,IACpC;AAAA,IACA;AAAA,EACF,CAAC;AACH;;;AC9SO,SAAS,uBAAuB,MAAc;AACnD,SAAO,iCAAiC,IAAI,oDAAoD,IAAI;AACtG;","names":["import_immer","import_reselect","createSelector","createDraftSafeSelector","args","noop","isActionCreator","stringify","getSerialize","thunkMiddleware","listener","middleware","reducer","createAsyncThunk","ReducerType","createSlice","reducer","name","reducerPath","createSelector","arg","original","noop","noop","task","result","noop","listener","addMiddleware","middleware","import_redux","selector"]}
Index: node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.production.min.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3 @@
+"use strict";var Ce=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var Pt=Object.prototype.hasOwnProperty;var Mt=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of wt(t))!Pt.call(e,a)&&a!==n&&Ce(e,a,{get:()=>t[a],enumerable:!(r=Rt(t,a))||r.enumerable});return e},M=(e,t,n)=>(xe(e,t,"default"),n&&xe(n,t,"default"));var bt=e=>xe(Ce({},"__esModule",{value:!0}),e);var E={};Mt(E,{ReducerType:()=>Ne,SHOULD_AUTOBATCH:()=>re,TaskAbortError:()=>D,Tuple:()=>V,addListener:()=>me,asyncThunkCreator:()=>rt,autoBatchEnhancer:()=>ae,buildCreateSlice:()=>je,clearAllListeners:()=>Ue,combineSlices:()=>Et,configureStore:()=>Ze,createAction:()=>v,createActionCreatorInvariantMiddleware:()=>Be,createAsyncThunk:()=>de,createDraftSafeSelector:()=>Y,createDraftSafeSelectorCreator:()=>Ee,createDynamicMiddleware:()=>xt,createEntityAdapter:()=>dt,createImmutableStateInvariantMiddleware:()=>He,createListenerMiddleware:()=>gt,createNextState:()=>C.produce,createReducer:()=>ie,createSelector:()=>ge.createSelector,createSelectorCreator:()=>O.createSelectorCreator,createSerializableStateInvariantMiddleware:()=>$e,createSlice:()=>at,current:()=>C.current,findNonSerializableValue:()=>Pe,formatProdErrorMessage:()=>R,freeze:()=>ke.freeze,isActionCreator:()=>ee,isAllOf:()=>z,isAnyOf:()=>L,isAsyncThunkAction:()=>ve,isDraft:()=>C.isDraft,isFluxStandardAction:()=>te,isFulfilled:()=>Ie,isImmutableDefault:()=>Ke,isPending:()=>Me,isPlain:()=>we,isRejected:()=>H,isRejectedWithValue:()=>be,lruMemoize:()=>ge.lruMemoize,miniSerializeError:()=>De,nanoid:()=>j,original:()=>ke.original,prepareAutoBatched:()=>Qe,removeListener:()=>Se,unwrapResult:()=>Oe,weakMapMemoize:()=>O.weakMapMemoize});module.exports=bt(E);M(E,require("redux"),module.exports);var ke=require("immer");var C=require("immer");var ge=require("reselect");var O=require("reselect");var Ee=(...e)=>{let t=(0,O.createSelectorCreator)(...e),n=Object.assign((...r)=>{let a=t(...r),o=(i,...h)=>a((0,C.isDraft)(i)?(0,C.current)(i):i,...h);return Object.assign(o,a),o},{withTypes:()=>n});return n},Y=Ee(O.weakMapMemoize);var P=require("redux");var Ge=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?P.compose:P.compose.apply(null,arguments)},mn=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__?window.__REDUX_DEVTOOLS_EXTENSION__:function(){return function(e){return e}};var ne=require("redux-thunk");var Z=e=>e&&typeof e.match=="function";function v(e,t){function n(...r){if(t){let a=t(...r);if(!a)throw new Error(R(0));return{type:e,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:e,payload:r[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=r=>(0,P.isAction)(r)&&r.type===e,n}function ee(e){return typeof e=="function"&&"type"in e&&Z(e)}function te(e){return(0,P.isAction)(e)&&Object.keys(e).every(It)}function It(e){return["type","payload","error","meta"].indexOf(e)>-1}function vt(e){let t=e?`${e}`.split("/"):[],n=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${n}())\` instead of \`dispatch(${n})\`. This is necessary even if the action has no payload.`}function Be(e={}){return()=>n=>r=>n(r)}var V=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...t){return super.concat.apply(this,t)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Re(e){return(0,C.isDraftable)(e)?(0,C.produce)(e,()=>{}):e}function N(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}function Ke(e){return typeof e!="object"||e==null||Object.isFrozen(e)}function He(e={}){if(1)return()=>r=>a=>r(a);var t,n}function we(e){let t=typeof e;return e==null||t==="string"||t==="boolean"||t==="number"||Array.isArray(e)||(0,P.isPlainObject)(e)}function Pe(e,t="",n=we,r,a=[],o){let i;if(!n(e))return{keyPath:t||"<root>",value:e};if(typeof e!="object"||e===null||o?.has(e))return!1;let h=r!=null?r(e):Object.entries(e),s=a.length>0;for(let[c,y]of h){let A=t?t+"."+c:c;if(!(s&&a.some(f=>f instanceof RegExp?f.test(A):A===f))){if(!n(y))return{keyPath:A,value:y};if(typeof y=="object"&&(i=Pe(y,A,n,r,a,o),i))return i}}return o&&qe(e)&&o.add(e),!1}function qe(e){if(!Object.isFrozen(e))return!1;for(let t of Object.values(e))if(!(typeof t!="object"||t===null)&&!qe(t))return!1;return!0}function $e(e={}){return()=>t=>n=>t(n)}function Dt(e){return typeof e=="boolean"}var Xe=()=>function(t){let{thunk:n=!0,immutableCheck:r=!0,serializableCheck:a=!0,actionCreatorCheck:o=!0}=t??{},i=new V;return n&&(Dt(n)?i.push(ne.thunk):i.push((0,ne.withExtraArgument)(n.extraArgument))),i};var re="RTK_autoBatch",Qe=()=>e=>({payload:e,meta:{[re]:!0}}),Je=e=>t=>{setTimeout(t,e)},ae=(e={type:"raf"})=>t=>(...n)=>{let r=t(...n),a=!0,o=!1,i=!1,h=new Set,s=e.type==="tick"?queueMicrotask:e.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:Je(10):e.type==="callback"?e.queueNotification:Je(e.timeout),c=()=>{i=!1,o&&(o=!1,h.forEach(y=>y()))};return Object.assign({},r,{subscribe(y){let A=()=>a&&y(),S=r.subscribe(A);return h.add(y),()=>{S(),h.delete(y)}},dispatch(y){try{return a=!y?.meta?.[re],o=!a,o&&(i||(i=!0,s(c))),r.dispatch(y)}finally{a=!0}}})};var Ye=e=>function(n){let{autoBatch:r=!0}=n??{},a=new V(e);return r&&a.push(ae(typeof r=="object"?r:void 0)),a};function Ze(e){let t=Xe(),{reducer:n=void 0,middleware:r,devTools:a=!0,duplicateMiddlewareCheck:o=!0,preloadedState:i=void 0,enhancers:h=void 0}=e||{},s;if(typeof n=="function")s=n;else if((0,P.isPlainObject)(n))s=(0,P.combineReducers)(n);else throw new Error(R(1));let c;typeof r=="function"?c=r(t):c=t();let y=P.compose;a&&(y=Ge({trace:!1,...typeof a=="object"&&a}));let A=(0,P.applyMiddleware)(...c),S=Ye(A),f=typeof h=="function"?h(S):S(),d=y(...f);return(0,P.createStore)(s,i,d)}function oe(e){let t={},n=[],r,a={addCase(o,i){let h=typeof o=="string"?o:o.type;if(!h)throw new Error(R(28));if(h in t)throw new Error(R(29));return t[h]=i,a},addAsyncThunk(o,i){return i.pending&&(t[o.pending.type]=i.pending),i.rejected&&(t[o.rejected.type]=i.rejected),i.fulfilled&&(t[o.fulfilled.type]=i.fulfilled),i.settled&&n.push({matcher:o.settled,reducer:i.settled}),a},addMatcher(o,i){return n.push({matcher:o,reducer:i}),a},addDefaultCase(o){return r=o,a}};return e(a),[t,n,r]}function Ot(e){return typeof e=="function"}function ie(e,t){let[n,r,a]=oe(t),o;if(Ot(e))o=()=>Re(e());else{let h=Re(e);o=()=>h}function i(h=o(),s){let c=[n[s.type],...r.filter(({matcher:y})=>y(s)).map(({reducer:y})=>y)];return c.filter(y=>!!y).length===0&&(c=[a]),c.reduce((y,A)=>{if(A)if((0,C.isDraft)(y)){let f=A(y,s);return f===void 0?y:f}else{if((0,C.isDraftable)(y))return(0,C.produce)(y,S=>A(S,s));{let S=A(y,s);if(S===void 0){if(y===null)return y;throw Error("A case reducer on a non-draftable value must not return undefined")}return S}}return y},h)}return i.getInitialState=o,i}var et=(e,t)=>Z(e)?e.match(t):e(t);function L(...e){return t=>e.some(n=>et(n,t))}function z(...e){return t=>e.every(n=>et(n,t))}function se(e,t){if(!e||!e.meta)return!1;let n=typeof e.meta.requestId=="string",r=t.indexOf(e.meta.requestStatus)>-1;return n&&r}function q(e){return typeof e[0]=="function"&&"pending"in e[0]&&"fulfilled"in e[0]&&"rejected"in e[0]}function Me(...e){return e.length===0?t=>se(t,["pending"]):q(e)?L(...e.map(t=>t.pending)):Me()(e[0])}function H(...e){return e.length===0?t=>se(t,["rejected"]):q(e)?L(...e.map(t=>t.rejected)):H()(e[0])}function be(...e){let t=n=>n&&n.meta&&n.meta.rejectedWithValue;return e.length===0?z(H(...e),t):q(e)?z(H(...e),t):be()(e[0])}function Ie(...e){return e.length===0?t=>se(t,["fulfilled"]):q(e)?L(...e.map(t=>t.fulfilled)):Ie()(e[0])}function ve(...e){return e.length===0?t=>se(t,["pending","fulfilled","rejected"]):q(e)?L(...e.flatMap(t=>[t.pending,t.rejected,t.fulfilled])):ve()(e[0])}var Nt="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",j=(e=21)=>{let t="",n=e;for(;n--;)t+=Nt[Math.random()*64|0];return t};var jt=["name","message","stack","code"],$=class{constructor(t,n){this.payload=t;this.meta=n}_type},ce=class{constructor(t,n){this.payload=t;this.meta=n}_type},De=e=>{if(typeof e=="object"&&e!==null){let t={};for(let n of jt)typeof e[n]=="string"&&(t[n]=e[n]);return t}return{message:String(e)}},tt="External signal was aborted",de=(()=>{function e(t,n,r){let a=v(t+"/fulfilled",(s,c,y,A)=>({payload:s,meta:{...A||{},arg:y,requestId:c,requestStatus:"fulfilled"}})),o=v(t+"/pending",(s,c,y)=>({payload:void 0,meta:{...y||{},arg:c,requestId:s,requestStatus:"pending"}})),i=v(t+"/rejected",(s,c,y,A,S)=>({payload:A,error:(r&&r.serializeError||De)(s||"Rejected"),meta:{...S||{},arg:y,requestId:c,rejectedWithValue:!!A,requestStatus:"rejected",aborted:s?.name==="AbortError",condition:s?.name==="ConditionError"}}));function h(s,{signal:c}={}){return(y,A,S)=>{let f=r?.idGenerator?r.idGenerator(s):j(),d=new AbortController,l,u;function p(T){u=T,d.abort()}c&&(c.aborted?p(tt):c.addEventListener("abort",()=>p(tt),{once:!0}));let g=async function(){let T;try{let k=r?.condition?.(s,{getState:A,extra:S});if(Ft(k)&&(k=await k),k===!1||d.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};let b=new Promise((x,w)=>{l=()=>{w({name:"AbortError",message:u||"Aborted"})},d.signal.addEventListener("abort",l,{once:!0})});y(o(f,s,r?.getPendingMeta?.({requestId:f,arg:s},{getState:A,extra:S}))),T=await Promise.race([b,Promise.resolve(n(s,{dispatch:y,getState:A,extra:S,requestId:f,signal:d.signal,abort:p,rejectWithValue:(x,w)=>new $(x,w),fulfillWithValue:(x,w)=>new ce(x,w)})).then(x=>{if(x instanceof $)throw x;return x instanceof ce?a(x.payload,f,s,x.meta):a(x,f,s)})])}catch(k){T=k instanceof $?i(null,f,s,k.payload,k.meta):i(k,f,s)}finally{l&&d.signal.removeEventListener("abort",l)}return r&&!r.dispatchConditionRejection&&i.match(T)&&T.meta.condition||y(T),T}();return Object.assign(g,{abort:p,requestId:f,arg:s,unwrap(){return g.then(Oe)}})}}return Object.assign(h,{pending:o,rejected:i,fulfilled:a,settled:L(i,a),typePrefix:t})}return e.withTypes=()=>e,e})();function Oe(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}function Ft(e){return e!==null&&typeof e=="object"&&typeof e.then=="function"}var nt=Symbol.for("rtk-slice-createasyncthunk"),rt={[nt]:de},Ne=(r=>(r.reducer="reducer",r.reducerWithPrepare="reducerWithPrepare",r.asyncThunk="asyncThunk",r))(Ne||{});function Vt(e,t){return`${e}/${t}`}function je({creators:e}={}){let t=e?.asyncThunk?.[nt];return function(r){let{name:a,reducerPath:o=a}=r;if(!a)throw new Error(R(11));typeof process<"u";let i=(typeof r.reducers=="function"?r.reducers(_t()):r.reducers)||{},h=Object.keys(i),s={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},c={addCase(T,m){let k=typeof T=="string"?T:T.type;if(!k)throw new Error(R(12));if(k in s.sliceCaseReducersByType)throw new Error(R(13));return s.sliceCaseReducersByType[k]=m,c},addMatcher(T,m){return s.sliceMatchers.push({matcher:T,reducer:m}),c},exposeAction(T,m){return s.actionCreators[T]=m,c},exposeCaseReducer(T,m){return s.sliceCaseReducersByName[T]=m,c}};h.forEach(T=>{let m=i[T],k={reducerName:T,type:Vt(a,T),createNotation:typeof r.reducers=="function"};Wt(m)?Gt(k,m,c,t):Ut(k,m,c)});function y(){let[T={},m=[],k=void 0]=typeof r.extraReducers=="function"?oe(r.extraReducers):[r.extraReducers],b={...T,...s.sliceCaseReducersByType};return ie(r.initialState,x=>{for(let w in b)x.addCase(w,b[w]);for(let w of s.sliceMatchers)x.addMatcher(w.matcher,w.reducer);for(let w of m)x.addMatcher(w.matcher,w.reducer);k&&x.addDefaultCase(k)})}let A=T=>T,S=new Map,f=new WeakMap,d;function l(T,m){return d||(d=y()),d(T,m)}function u(){return d||(d=y()),d.getInitialState()}function p(T,m=!1){function k(x){let w=x[T];return typeof w>"u"&&m&&(w=N(f,k,u)),w}function b(x=A){let w=N(S,m,()=>new WeakMap);return N(w,x,()=>{let K={};for(let[Q,W]of Object.entries(r.selectors??{}))K[Q]=Lt(W,x,()=>N(f,x,u),m);return K})}return{reducerPath:T,getSelectors:b,get selectors(){return b(k)},selectSlice:k}}let g={name:a,reducer:l,actions:s.actionCreators,caseReducers:s.sliceCaseReducersByName,getInitialState:u,...p(o),injectInto(T,{reducerPath:m,...k}={}){let b=m??o;return T.inject({reducerPath:b,reducer:l},k),{...g,...p(b,!0)}}};return g}}function Lt(e,t,n,r){function a(o,...i){let h=t(o);return typeof h>"u"&&r&&(h=n()),e(h,...i)}return a.unwrapped=e,a}var at=je();function _t(){function e(t,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...n}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...n){return t(...n)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:n}},asyncThunk:e}}function Ut({type:e,reducerName:t,createNotation:n},r,a){let o,i;if("reducer"in r){if(n&&!zt(r))throw new Error(R(17));o=r.reducer,i=r.prepare}else o=r;a.addCase(e,o).exposeCaseReducer(t,o).exposeAction(t,i?v(e,i):v(e))}function Wt(e){return e._reducerDefinitionType==="asyncThunk"}function zt(e){return e._reducerDefinitionType==="reducerWithPrepare"}function Gt({type:e,reducerName:t},n,r,a){if(!a)throw new Error(R(18));let{payloadCreator:o,fulfilled:i,pending:h,rejected:s,settled:c,options:y}=n,A=a(e,o,y);r.exposeAction(t,A),i&&r.addCase(A.fulfilled,i),h&&r.addCase(A.pending,h),s&&r.addCase(A.rejected,s),c&&r.addMatcher(A.settled,c),r.exposeCaseReducer(t,{fulfilled:i||ue,pending:h||ue,rejected:s||ue,settled:c||ue})}function ue(){}function Bt(){return{ids:[],entities:{}}}function ot(e){function t(n={},r){let a=Object.assign(Bt(),n);return r?e.setAll(a,r):a}return{getInitialState:t}}function it(){function e(t,n={}){let{createSelector:r=Y}=n,a=A=>A.ids,o=A=>A.entities,i=r(a,o,(A,S)=>A.map(f=>S[f])),h=(A,S)=>S,s=(A,S)=>A[S],c=r(a,A=>A.length);if(!t)return{selectIds:a,selectEntities:o,selectAll:i,selectTotal:c,selectById:r(o,h,s)};let y=r(t,o);return{selectIds:r(t,a),selectEntities:y,selectAll:r(t,i),selectTotal:r(t,c),selectById:r(y,h,s)}}return{getSelectors:e}}var Kt=C.isDraft;function st(e){let t=I((n,r)=>e(r));return function(r){return t(r,void 0)}}function I(e){return function(n,r){function a(i){return te(i)}let o=i=>{a(r)?e(r.payload,i):e(r,i)};return Kt(n)?(o(n),n):(0,C.produce)(n,o)}}function _(e,t){return t(e)}function F(e){return Array.isArray(e)||(e=Object.values(e)),e}function X(e){return(0,C.isDraft)(e)?(0,C.current)(e):e}function le(e,t,n){e=F(e);let r=X(n.ids),a=new Set(r),o=[],i=new Set([]),h=[];for(let s of e){let c=_(s,t);a.has(c)||i.has(c)?h.push({id:c,changes:s}):(i.add(c),o.push(s))}return[o,h,r]}function pe(e){function t(d,l){let u=_(d,e);u in l.entities||(l.ids.push(u),l.entities[u]=d)}function n(d,l){d=F(d);for(let u of d)t(u,l)}function r(d,l){let u=_(d,e);u in l.entities||l.ids.push(u),l.entities[u]=d}function a(d,l){d=F(d);for(let u of d)r(u,l)}function o(d,l){d=F(d),l.ids=[],l.entities={},n(d,l)}function i(d,l){return h([d],l)}function h(d,l){let u=!1;d.forEach(p=>{p in l.entities&&(delete l.entities[p],u=!0)}),u&&(l.ids=l.ids.filter(p=>p in l.entities))}function s(d){Object.assign(d,{ids:[],entities:{}})}function c(d,l,u){let p=u.entities[l.id];if(p===void 0)return!1;let g=Object.assign({},p,l.changes),T=_(g,e),m=T!==l.id;return m&&(d[l.id]=T,delete u.entities[l.id]),u.entities[T]=g,m}function y(d,l){return A([d],l)}function A(d,l){let u={},p={};d.forEach(T=>{T.id in l.entities&&(p[T.id]={id:T.id,changes:{...p[T.id]?.changes,...T.changes}})}),d=Object.values(p),d.length>0&&d.filter(m=>c(u,m,l)).length>0&&(l.ids=Object.values(l.entities).map(m=>_(m,e)))}function S(d,l){return f([d],l)}function f(d,l){let[u,p]=le(d,e,l);n(u,l),A(p,l)}return{removeAll:st(s),addOne:I(t),addMany:I(n),setOne:I(r),setMany:I(a),setAll:I(o),updateOne:I(y),updateMany:I(A),upsertOne:I(S),upsertMany:I(f),removeOne:I(i),removeMany:I(h)}}function Ht(e,t,n){let r=0,a=e.length;for(;r<a;){let o=r+a>>>1,i=e[o];n(t,i)>=0?r=o+1:a=o}return r}function qt(e,t,n){let r=Ht(e,t,n);return e.splice(r,0,t),e}function ct(e,t){let{removeOne:n,removeMany:r,removeAll:a}=pe(e);function o(u,p){return i([u],p)}function i(u,p,g){u=F(u);let T=new Set(g??X(p.ids)),m=new Set,k=u.filter(b=>{let x=_(b,e),w=!m.has(x);return w&&m.add(x),!T.has(x)&&w});k.length!==0&&l(p,k)}function h(u,p){return s([u],p)}function s(u,p){let g={};if(u=F(u),u.length!==0){for(let T of u){let m=e(T);g[m]=T,delete p.entities[m]}u=F(g),l(p,u)}}function c(u,p){u=F(u),p.entities={},p.ids=[],i(u,p,[])}function y(u,p){return A([u],p)}function A(u,p){let g=!1,T=!1;for(let m of u){let k=p.entities[m.id];if(!k)continue;g=!0,Object.assign(k,m.changes);let b=e(k);if(m.id!==b){T=!0,delete p.entities[m.id];let x=p.ids.indexOf(m.id);p.ids[x]=b,p.entities[b]=k}}g&&l(p,[],g,T)}function S(u,p){return f([u],p)}function f(u,p){let[g,T,m]=le(u,e,p);g.length&&i(g,p,m),T.length&&A(T,p)}function d(u,p){if(u.length!==p.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==p[g])return!1;return!0}let l=(u,p,g,T)=>{let m=X(u.entities),k=X(u.ids),b=u.entities,x=k;T&&(x=new Set(k));let w=[];for(let W of x){let ze=m[W];ze&&w.push(ze)}let K=w.length===0;for(let W of p)b[e(W)]=W,K||qt(w,W,t);K?w=p.slice().sort(t):g&&w.sort(t);let Q=w.map(e);d(k,Q)||(u.ids=Q)};return{removeOne:n,removeMany:r,removeAll:a,addOne:I(o),updateOne:I(y),upsertOne:I(S),setOne:I(h),setMany:I(s),setAll:I(c),addMany:I(i),updateMany:I(A),upsertMany:I(f)}}function dt(e={}){let{selectId:t,sortComparer:n}={sortComparer:!1,selectId:i=>i.id,...e},r=n?ct(t,n):pe(t),a=ot(r),o=it();return{selectId:t,sortComparer:n,...a,...o,...r}}var $t="task",ut="listener",lt="completed",Fe="cancelled",pt=`task-${Fe}`,ft=`task-${lt}`,fe=`${ut}-${Fe}`,yt=`${ut}-${lt}`,D=class{constructor(t){this.code=t;this.message=`${$t} ${Fe} (reason: ${t})`}name="TaskAbortError";message};var ye=(e,t)=>{if(typeof e!="function")throw new TypeError(R(32))},G=()=>{},he=(e,t=G)=>(e.catch(t),e),Ae=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t));var U=e=>{if(e.aborted)throw new D(e.reason)};function Ve(e,t){let n=G;return new Promise((r,a)=>{let o=()=>a(new D(e.reason));if(e.aborted){o();return}n=Ae(e,o),t.finally(()=>n()).then(r,a)}).finally(()=>{n=G})}var ht=async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(n){return{status:n instanceof D?"cancelled":"rejected",error:n}}finally{t?.()}},J=e=>t=>he(Ve(e,t).then(n=>(U(e),n))),Le=e=>{let t=J(e);return n=>t(new Promise(r=>setTimeout(r,n)))};var{assign:B}=Object,At={},Te="listenerMiddleware",Xt=(e,t)=>{let n=r=>Ae(e,()=>r.abort(e.reason));return(r,a)=>{ye(r,"taskExecutor");let o=new AbortController;n(o);let i=ht(async()=>{U(e),U(o.signal);let h=await r({pause:J(o.signal),delay:Le(o.signal),signal:o.signal});return U(o.signal),h},()=>o.abort(ft));return a?.autoJoin&&t.push(i.catch(G)),{result:J(e)(i),cancel(){o.abort(pt)}}}},Jt=(e,t)=>{let n=async(r,a)=>{U(t);let o=()=>{},h=[new Promise((s,c)=>{let y=e({predicate:r,effect:(A,S)=>{S.unsubscribe(),s([A,S.getState(),S.getOriginalState()])}});o=()=>{y(),c()}})];a!=null&&h.push(new Promise(s=>setTimeout(s,a,null)));try{let s=await Ve(t,Promise.race(h));return U(t),s}finally{o()}};return(r,a)=>he(n(r,a))},St=e=>{let{type:t,actionCreator:n,matcher:r,predicate:a,effect:o}=e;if(t)a=v(t).match;else if(n)t=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(R(21));return ye(o,"options.listener"),{predicate:a,type:t,effect:o}},kt=B(e=>{let{type:t,predicate:n,effect:r}=St(e);return{id:j(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(R(22))}}},{withTypes:()=>kt}),Tt=(e,t)=>{let{type:n,effect:r,predicate:a}=St(t);return Array.from(e.values()).find(o=>(typeof n=="string"?o.type===n:o.predicate===a)&&o.effect===r)},_e=e=>{e.pending.forEach(t=>{t.abort(fe)})},Qt=(e,t)=>()=>{for(let n of t.keys())_e(n);e.clear()},mt=(e,t,n)=>{try{e(t,n)}catch(r){setTimeout(()=>{throw r},0)}},me=B(v(`${Te}/add`),{withTypes:()=>me}),Ue=v(`${Te}/removeAll`),Se=B(v(`${Te}/remove`),{withTypes:()=>Se}),Yt=(...e)=>{console.error(`${Te}/error`,...e)},gt=(e={})=>{let t=new Map,n=new Map,r=f=>{let d=n.get(f)??0;n.set(f,d+1)},a=f=>{let d=n.get(f)??1;d===1?n.delete(f):n.set(f,d-1)},{extra:o,onError:i=Yt}=e;ye(i,"onError");let h=f=>(f.unsubscribe=()=>t.delete(f.id),t.set(f.id,f),d=>{f.unsubscribe(),d?.cancelActive&&_e(f)}),s=f=>{let d=Tt(t,f)??kt(f);return h(d)};B(s,{withTypes:()=>s});let c=f=>{let d=Tt(t,f);return d&&(d.unsubscribe(),f.cancelActive&&_e(d)),!!d};B(c,{withTypes:()=>c});let y=async(f,d,l,u)=>{let p=new AbortController,g=Jt(s,p.signal),T=[];try{f.pending.add(p),r(f),await Promise.resolve(f.effect(d,B({},l,{getOriginalState:u,condition:(m,k)=>g(m,k).then(Boolean),take:g,delay:Le(p.signal),pause:J(p.signal),extra:o,signal:p.signal,fork:Xt(p.signal,T),unsubscribe:f.unsubscribe,subscribe:()=>{t.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((m,k,b)=>{m!==p&&(m.abort(fe),b.delete(m))})},cancel:()=>{p.abort(fe),f.pending.delete(p)},throwIfCancelled:()=>{U(p.signal)}})))}catch(m){m instanceof D||mt(i,m,{raisedBy:"effect"})}finally{await Promise.all(T),p.abort(yt),a(f),f.pending.delete(p)}},A=Qt(t,n);return{middleware:f=>d=>l=>{if(!(0,P.isAction)(l))return d(l);if(me.match(l))return s(l.payload);if(Ue.match(l)){A();return}if(Se.match(l))return c(l.payload);let u=f.getState(),p=()=>{if(u===At)throw new Error(R(23));return u},g;try{if(g=d(l),t.size>0){let T=f.getState(),m=Array.from(t.values());for(let k of m){let b=!1;try{b=k.predicate(l,T,u)}catch(x){b=!1,mt(i,x,{raisedBy:"predicate"})}b&&y(k,l,f,p)}}}finally{u=At}return g},startListening:s,stopListening:c,clearListeners:A}};var Zt=e=>({middleware:e,applied:new Map}),en=e=>t=>t?.meta?.instanceId===e,xt=()=>{let e=j(),t=new Map,n=Object.assign(v("dynamicMiddleware/add",(...h)=>({payload:h,meta:{instanceId:e}})),{withTypes:()=>n}),r=Object.assign(function(...s){s.forEach(c=>{N(t,c,Zt)})},{withTypes:()=>r}),a=h=>{let s=Array.from(t.values()).map(c=>N(c.applied,h,c.middleware));return(0,P.compose)(...s)},o=z(n,en(e));return{middleware:h=>s=>c=>o(c)?(r(...c.payload),h.dispatch):a(h)(s)(c),addMiddleware:r,withMiddleware:n,instanceId:e}};var Ct=require("redux");var tn=e=>"reducerPath"in e&&typeof e.reducerPath=="string",nn=e=>e.flatMap(t=>tn(t)?[[t.reducerPath,t.reducer]]:Object.entries(t)),We=Symbol.for("rtk-state-proxy-original"),rn=e=>!!e&&!!e[We],an=new WeakMap,on=(e,t,n)=>N(an,e,()=>new Proxy(e,{get:(r,a,o)=>{if(a===We)return r;let i=Reflect.get(r,a,o);if(typeof i>"u"){let h=n[a];if(typeof h<"u")return h;let s=t[a];if(s){let c=s(void 0,{type:j()});if(typeof c>"u")throw new Error(R(24));return n[a]=c,c}}return i}})),sn=e=>{if(!rn(e))throw new Error(R(25));return e[We]},cn={},dn=(e=cn)=>e;function Et(...e){let t=Object.fromEntries(nn(e)),n=()=>Object.keys(t).length?(0,Ct.combineReducers)(t):dn,r=n();function a(s,c){return r(s,c)}a.withLazyLoadedSlices=()=>a;let o={},i=(s,c={})=>{let{reducerPath:y,reducer:A}=s,S=t[y];return!c.overrideExisting&&S&&S!==A?(typeof process<"u",a):(c.overrideExisting&&S!==A&&delete o[y],t[y]=A,r=n(),a)},h=Object.assign(function(c,y){return function(S,...f){return c(on(y?y(S,...f):S,t,o),...f)}},{original:sn});return Object.assign(a,{inject:i,selector:h})}function R(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}0&&(module.exports={ReducerType,SHOULD_AUTOBATCH,TaskAbortError,Tuple,addListener,asyncThunkCreator,autoBatchEnhancer,buildCreateSlice,clearAllListeners,combineSlices,configureStore,createAction,createActionCreatorInvariantMiddleware,createAsyncThunk,createDraftSafeSelector,createDraftSafeSelectorCreator,createDynamicMiddleware,createEntityAdapter,createImmutableStateInvariantMiddleware,createListenerMiddleware,createNextState,createReducer,createSelector,createSelectorCreator,createSerializableStateInvariantMiddleware,createSlice,current,findNonSerializableValue,formatProdErrorMessage,freeze,isActionCreator,isAllOf,isAnyOf,isAsyncThunkAction,isDraft,isFluxStandardAction,isFulfilled,isImmutableDefault,isPending,isPlain,isRejected,isRejectedWithValue,lruMemoize,miniSerializeError,nanoid,original,prepareAutoBatched,removeListener,unwrapResult,weakMapMemoize,...require("redux")});
+//# sourceMappingURL=redux-toolkit.production.min.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.production.min.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/index.ts","../../src/immerImports.ts","../../src/reselectImports.ts","../../src/createDraftSafeSelector.ts","../../src/reduxImports.ts","../../src/devtoolsExtension.ts","../../src/getDefaultMiddleware.ts","../../src/tsHelpers.ts","../../src/createAction.ts","../../src/actionCreatorInvariantMiddleware.ts","../../src/utils.ts","../../src/immutableStateInvariantMiddleware.ts","../../src/serializableStateInvariantMiddleware.ts","../../src/autoBatchEnhancer.ts","../../src/getDefaultEnhancers.ts","../../src/configureStore.ts","../../src/mapBuilders.ts","../../src/createReducer.ts","../../src/matchers.ts","../../src/nanoid.ts","../../src/createAsyncThunk.ts","../../src/createSlice.ts","../../src/entities/entity_state.ts","../../src/entities/state_selectors.ts","../../src/entities/state_adapter.ts","../../src/entities/utils.ts","../../src/entities/unsorted_state_adapter.ts","../../src/entities/sorted_state_adapter.ts","../../src/entities/create_adapter.ts","../../src/listenerMiddleware/exceptions.ts","../../src/listenerMiddleware/utils.ts","../../src/listenerMiddleware/task.ts","../../src/listenerMiddleware/index.ts","../../src/dynamicMiddleware/index.ts","../../src/combineSlices.ts","../../src/formatProdErrorMessage.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage';\nexport * from 'redux';\nexport { freeze, original } from 'immer';\nexport { createNextState, current, isDraft } from './immerImports';\nexport type { Draft, WritableDraft } from 'immer';\nexport { createSelector, lruMemoize } from 'reselect';\nexport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport type { Selector, OutputSelector } from 'reselect';\nexport { createDraftSafeSelector, createDraftSafeSelectorCreator } from './createDraftSafeSelector';\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';\nexport {\n// js\nconfigureStore } from './configureStore';\nexport type {\n// types\nConfigureStoreOptions, EnhancedStore } from './configureStore';\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension';\nexport {\n// js\ncreateAction, isActionCreator, isFSA as isFluxStandardAction } from './createAction';\nexport type {\n// types\nPayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction } from './createAction';\nexport {\n// js\ncreateReducer } from './createReducer';\nexport type {\n// types\nActions, CaseReducer, CaseReducers } from './createReducer';\nexport {\n// js\ncreateSlice, buildCreateSlice, asyncThunkCreator, ReducerType } from './createSlice';\nexport type {\n// types\nCreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, ReducerCreators, SliceSelectors } from './createSlice';\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nexport {\n// js\ncreateImmutableStateInvariantMiddleware, isImmutableDefault } from './immutableStateInvariantMiddleware';\nexport type {\n// types\nImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\nexport {\n// js\ncreateSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nSerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nActionReducerMapBuilder, AsyncThunkReducers } from './mapBuilders';\nexport { Tuple } from './utils';\nexport { createEntityAdapter } from './entities/create_adapter';\nexport type { EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer } from './entities/models';\nexport { createAsyncThunk, unwrapResult, miniSerializeError } from './createAsyncThunk';\nexport type { AsyncThunk, AsyncThunkConfig, AsyncThunkDispatchConfig, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, GetState, GetThunkAPI, SerializedError, CreateAsyncThunkFunction } from './createAsyncThunk';\nexport {\n// js\nisAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue } from './matchers';\nexport type {\n// types\nActionMatchingAllOf, ActionMatchingAnyOf } from './matchers';\nexport { nanoid } from './nanoid';\nexport type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult } from './listenerMiddleware/index';\nexport type { AnyListenerPredicate } from './listenerMiddleware/types';\nexport { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError } from './listenerMiddleware/index';\nexport type { AddMiddleware, DynamicDispatch, DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './dynamicMiddleware/types';\nexport { createDynamicMiddleware } from './dynamicMiddleware/index';\nexport { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer } from './autoBatchEnhancer';\nexport type { AutoBatchOptions } from './autoBatchEnhancer';\nexport { combineSlices } from './combineSlices';\nexport type { CombinedSliceReducer, WithSlice, WithSlicePreloadedState } from './combineSlices';\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers';\nexport { formatProdErrorMessage } from './formatProdErrorMessage';","export { current, isDraft, produce as createNextState, isDraftable, setUseStrictIteration } from 'immer';","export { createSelectorCreator, weakMapMemoize } from 'reselect';","import { current, isDraft } from './immerImports';\nimport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (...args: unknown[]) => {\n  const createSelector = (createSelectorCreator as any)(...args);\n  const createDraftSafeSelector = Object.assign((...args: unknown[]) => {\n    const selector = createSelector(...args);\n    const wrappedSelector = (value: unknown, ...rest: unknown[]) => selector(isDraft(value) ? current(value) : value, ...rest);\n    Object.assign(wrappedSelector, selector);\n    return wrappedSelector as any;\n  }, {\n    withTypes: () => createDraftSafeSelector\n  });\n  return createDraftSafeSelector;\n};\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector = /* @__PURE__ */\ncreateDraftSafeSelectorCreator(weakMapMemoize);","export { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from 'redux';","import type { Action, ActionCreator, StoreEnhancer } from 'redux';\nimport { compose } from './reduxImports';\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string;\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | {\n    [key: string]: ActionCreator<any>;\n  };\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number;\n  /**\n   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\n   *\n   * @default 50\n   */\n  maxAge?: number;\n  /**\n   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?: boolean | {\n    /**\n     * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n     * - `false` - will handle also circular references.\n     * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n     * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n     *   For each of them you can indicate if to include (by setting as `true`).\n     *   For `function` key you can also specify a custom function which handles serialization.\n     *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n     */\n    options?: undefined | boolean | {\n      date?: true;\n      regex?: true;\n      undefined?: true;\n      error?: true;\n      symbol?: true;\n      map?: true;\n      set?: true;\n      function?: true | ((fn: (...args: any[]) => any) => string);\n    };\n    /**\n     * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\n     * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n     * key. So you can deserialize it back while importing or persisting data.\n     * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\n     */\n    replacer?: (key: string, value: unknown) => any;\n    /**\n     * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n     * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n     * as an example on how to serialize special data types and get them back.\n     */\n    reviver?: (key: string, value: unknown) => any;\n    /**\n     * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n     * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n     * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n     */\n    immutable?: any;\n    /**\n     * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n     */\n    refs?: any;\n  };\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A;\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S;\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[];\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[];\n  /**\n   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean;\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean;\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string;\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean;\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean;\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean;\n  /**\n   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean;\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean;\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean;\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean;\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom';\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom';\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean;\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean;\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean;\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean;\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean;\n  };\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string);\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number;\n}\ntype Compose = typeof compose;\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose;\n  <StoreExt extends {}>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\n  if (arguments.length === 0) return undefined;\n  if (typeof arguments[0] === 'object') return compose;\n  return compose.apply(null, arguments as any as Function[]);\n};\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>;\n} = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION__ : function () {\n  return function (noop) {\n    return noop;\n  };\n};","import type { Middleware, UnknownAction } from 'redux';\nimport type { ThunkMiddleware } from 'redux-thunk';\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk';\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware';\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware';\nimport type { ExcludeFromTuple } from './tsHelpers';\nimport { Tuple } from './utils';\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean';\n}\ninterface ThunkOptions<E = any> {\n  extraArgument: E;\n}\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions;\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;\n}\nexport type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {\n  thunk: false;\n} ? never : O extends {\n  thunk: {\n    extraArgument: infer E;\n  };\n} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;\nexport type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {\n  thunk: true;\n  immutableCheck: true;\n  serializableCheck: true;\n  actionCreatorCheck: true;\n}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;\nexport const buildGetDefaultMiddleware = <S = any,>(): GetDefaultMiddleware<S> => function getDefaultMiddleware(options) {\n  const {\n    thunk = true,\n    immutableCheck = true,\n    serializableCheck = true,\n    actionCreatorCheck = true\n  } = options ?? {};\n  let middlewareArray = new Tuple<Middleware[]>();\n  if (thunk) {\n    if (isBoolean(thunk)) {\n      middlewareArray.push(thunkMiddleware);\n    } else {\n      middlewareArray.push(withExtraArgument(thunk.extraArgument));\n    }\n  }\n  if (process.env.NODE_ENV !== 'production') {\n    if (immutableCheck) {\n      /* PROD_START_REMOVE_UMD */\n      let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(immutableCheck)) {\n        immutableOptions = immutableCheck;\n      }\n      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n      /* PROD_STOP_REMOVE_UMD */\n    }\n    if (serializableCheck) {\n      let serializableOptions: SerializableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(serializableCheck)) {\n        serializableOptions = serializableCheck;\n      }\n      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n    }\n    if (actionCreatorCheck) {\n      let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {};\n      if (!isBoolean(actionCreatorCheck)) {\n        actionCreatorOptions = actionCreatorCheck;\n      }\n      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n    }\n  }\n  return middlewareArray as any;\n};","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport { isAction } from './reduxImports';\nimport type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<P = void, T extends string = string, M = never, E = never> = {\n  payload: P;\n  type: T;\n} & ([M] extends [never] ? {} : {\n  meta: M;\n}) & ([E] extends [never] ? {} : {\n  error: E;\n});\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> = ((...args: any[]) => {\n  payload: P;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  error: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n  error: any;\n});\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {\n  error: infer E;\n} ? E : never, ReturnType<PA> extends {\n  meta: infer M;\n} ? M : never> : void;\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T;\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>;\n};\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>;\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>;\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>;\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>,\n// else\nIsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>,\n// else\nIfVoid<P, ActionCreatorWithoutPayload<T>,\n// else\nIfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>,\n// else\nActionCreatorWithPayload<P, T>>>>>>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args);\n      if (!prepared) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(0) : 'prepareAction did not return an object');\n      }\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && {\n          meta: prepared.meta\n        }),\n        ...('error' in prepared && {\n          error: prepared.error\n        })\n      };\n    }\n    return {\n      type,\n      payload: args[0]\n    };\n  }\n  actionCreator.toString = () => `${type}`;\n  actionCreator.type = type;\n  actionCreator.match = (action: unknown): action is PayloadAction => isAction(action) && action.type === type;\n  return actionCreator;\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function {\n  return typeof action === 'function' && 'type' in action &&\n  // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n  hasMatchFunction(action as any);\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string;\n  payload?: unknown;\n  error?: unknown;\n  meta?: unknown;\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1;\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends ((...args: any[]) => any) ? True : False;","import type { Middleware } from 'redux';\nimport { isActionCreator as isRTKAction } from './createAction';\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & {\n    type?: unknown;\n  };\n}\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : [];\n  const actionName = splitType[splitType.length - 1] || 'actionCreator';\n  return `Detected an action creator with type \"${type || 'unknown'}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nexport function createActionCreatorInvariantMiddleware(options: ActionCreatorInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  }\n  const {\n    isActionCreator = isRTKAction\n  } = options;\n  return () => next => action => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type));\n    }\n    return next(action);\n  };\n}","import { createNextState, isDraftable } from './immerImports';\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0;\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now();\n      try {\n        return fn();\n      } finally {\n        const finished = Date.now();\n        elapsed += finished - started;\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n      }\n    }\n  };\n}\nexport function delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {\n  constructor(length: number);\n  constructor(...items: Items);\n  constructor(...items: any[]) {\n    super(...items);\n    Object.setPrototypeOf(this, Tuple.prototype);\n  }\n  static override get [Symbol.species]() {\n    return Tuple as any;\n  }\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr);\n  }\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this));\n    }\n    return new Tuple(...arr.concat(this));\n  }\n}\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val;\n}\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | PromiseLike<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve: any;\n  let reject: any;\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve,\n    reject\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Middleware } from 'redux';\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware';\nimport { getTimeMeasureUtils } from './utils';\ntype EntryProcessor = (key: string, value: any) => any;\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value);\n}\nexport function trackForMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths | undefined, obj: any) {\n  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);\n    }\n  };\n}\ninterface TrackedProperty {\n  value: any;\n  children: Record<string, any>;\n}\nfunction trackProperties(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], obj: Record<string, any>, path: string = '', checkedObjects: Set<Record<string, any>> = new Set()) {\n  const tracked: Partial<TrackedProperty> = {\n    value: obj\n  };\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj);\n    tracked.children = {};\n    const hasIgnoredPaths = ignoredPaths.length > 0;\n    for (const key in obj) {\n      const nestedPath = path ? path + '.' + key : key;\n      if (hasIgnoredPaths) {\n        const hasMatches = ignoredPaths.some(ignored => {\n          if (ignored instanceof RegExp) {\n            return ignored.test(nestedPath);\n          }\n          return nestedPath === ignored;\n        });\n        if (hasMatches) {\n          continue;\n        }\n      }\n      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);\n    }\n  }\n  return tracked as TrackedProperty;\n}\nfunction detectMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, path: string = ''): {\n  wasMutated: boolean;\n  path?: string;\n} {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined;\n  const sameRef = prevObj === obj;\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return {\n      wasMutated: true,\n      path\n    };\n  }\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return {\n      wasMutated: false\n    };\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {};\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true;\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true;\n  }\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n    if (result.wasMutated) {\n      return result;\n    }\n  }\n  return {\n    wasMutated: false\n  };\n}\ntype IsImmutableFunc = (value: any) => boolean;\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc;\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths;\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number;\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(options: ImmutableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    function stringify(obj: any, serializer?: EntryProcessor, indent?: string | number, decycler?: EntryProcessor): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\n    }\n    function getSerialize(serializer?: EntryProcessor, decycler?: EntryProcessor): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = [];\n      if (!decycler) decycler = function (_: string, value: any) {\n        if (stack[0] === value) return '[Circular ~]';\n        return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n      };\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this);\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value);\n        } else stack.push(value);\n        return serializer == null ? value : serializer.call(this, key, value);\n      };\n    }\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32\n    } = options;\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n    return ({\n      getState\n    }) => {\n      let state = getState();\n      let tracker = track(state);\n      let result;\n      return next => action => {\n        const measureUtils = getTimeMeasureUtils(warnAfter, 'ImmutableStateInvariantMiddleware');\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ''}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        const dispatchedAction = next(action);\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ''}. Take a look at the reducer(s) handling the action ${stringify(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n        return dispatchedAction;\n      };\n    };\n  }\n}","import type { Middleware } from 'redux';\nimport { isAction, isPlainObject } from './reduxImports';\nimport { getTimeMeasureUtils } from './utils';\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val;\n  return val == null || type === 'string' || type === 'boolean' || type === 'number' || Array.isArray(val) || isPlainObject(val);\n}\ninterface NonSerializableValue {\n  keyPath: string;\n  value: unknown;\n}\nexport type IgnorePaths = readonly (string | RegExp)[];\n\n/**\n * @public\n */\nexport function findNonSerializableValue(value: unknown, path: string = '', isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], cache?: WeakSet<object>): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false;\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value\n    };\n  }\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  if (cache?.has(value)) return false;\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue\n      };\n    }\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n      if (foundNestedSerializable) {\n        return foundNestedSerializable;\n      }\n    }\n  }\n  if (cache && isNestedFrozen(value)) cache.add(value);\n  return false;\n}\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false;\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue;\n    if (!isNestedFrozen(nestedValue)) return false;\n  }\n  return true;\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean;\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][];\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[];\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number;\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean;\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean;\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean;\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(options: SerializableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false\n    } = options;\n    const cache: WeakSet<object> | undefined = !disableCache && WeakSet ? new WeakSet() : undefined;\n    return storeAPI => next => action => {\n      if (!isAction(action)) {\n        return next(action);\n      }\n      const result = next(action);\n      const measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type as any) !== -1)) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(action, '', isSerializable, getEntries, ignoredActionPaths, cache);\n          if (foundActionNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundActionNonSerializableValue;\n            console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, '\\nTake a look at the logic that dispatched this action: ', action, '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)');\n          }\n        });\n      }\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState();\n          const foundStateNonSerializableValue = findNonSerializableValue(state, '', isSerializable, getEntries, ignoredPaths, cache);\n          if (foundStateNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundStateNonSerializableValue;\n            console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n      }\n      return result;\n    };\n  }\n}","import type { StoreEnhancer } from 'redux';\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch';\nexport const prepareAutoBatched = <T,>() => (payload: T): {\n  payload: T;\n  meta: unknown;\n} => ({\n  payload,\n  meta: {\n    [SHOULD_AUTOBATCH]: true\n  }\n});\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout);\n  };\n};\nexport type AutoBatchOptions = {\n  type: 'tick';\n} | {\n  type: 'timer';\n  timeout: number;\n} | {\n  type: 'raf';\n} | {\n  type: 'callback';\n  queueNotification: (notify: () => void) => void;\n};\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer = (options: AutoBatchOptions = {\n  type: 'raf'\n}): StoreEnhancer => next => (...args) => {\n  const store = next(...args);\n  let notifying = true;\n  let shouldNotifyAtEndOfTick = false;\n  let notificationQueued = false;\n  const listeners = new Set<() => void>();\n  const queueCallback = options.type === 'tick' ? queueMicrotask : options.type === 'raf' ?\n  // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n  typeof window !== 'undefined' && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === 'callback' ? options.queueNotification : createQueueWithTimer(options.timeout);\n  const notifyListeners = () => {\n    // We're running at the end of the event loop tick.\n    // Run the real listener callbacks to actually update the UI.\n    notificationQueued = false;\n    if (shouldNotifyAtEndOfTick) {\n      shouldNotifyAtEndOfTick = false;\n      listeners.forEach(l => l());\n    }\n  };\n  return Object.assign({}, store, {\n    // Override the base `store.subscribe` method to keep original listeners\n    // from running if we're delaying notifications\n    subscribe(listener: () => void) {\n      // Each wrapped listener will only call the real listener if\n      // the `notifying` flag is currently active when it's called.\n      // This lets the base store work as normal, while the actual UI\n      // update becomes controlled by this enhancer.\n      const wrappedListener: typeof listener = () => notifying && listener();\n      const unsubscribe = store.subscribe(wrappedListener);\n      listeners.add(listener);\n      return () => {\n        unsubscribe();\n        listeners.delete(listener);\n      };\n    },\n    // Override the base `store.dispatch` method so that we can check actions\n    // for the `shouldAutoBatch` flag and determine if batching is active\n    dispatch(action: any) {\n      try {\n        // If the action does _not_ have the `shouldAutoBatch` flag,\n        // we resume/continue normal notify-after-each-dispatch behavior\n        notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n        // If a `notifyListeners` microtask was queued, you can't cancel it.\n        // Instead, we set a flag so that it's a no-op when it does run\n        shouldNotifyAtEndOfTick = !notifying;\n        if (shouldNotifyAtEndOfTick) {\n          // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n          // a microtask to notify listeners at the end of the event loop tick.\n          // Make sure we only enqueue this _once_ per tick.\n          if (!notificationQueued) {\n            notificationQueued = true;\n            queueCallback(notifyListeners);\n          }\n        }\n        // Go ahead and process the action as usual, including reducers.\n        // If normal notification behavior is enabled, the store will notify\n        // all of its own listeners, and the wrapper callbacks above will\n        // see `notifying` is true and pass on to the real listener callbacks.\n        // If we're \"batching\" behavior, then the wrapped callbacks will\n        // bail out, causing the base store notification behavior to be no-ops.\n        return store.dispatch(action);\n      } finally {\n        // Assume we're back to normal behavior after each action\n        notifying = true;\n      }\n    }\n  });\n};","import type { StoreEnhancer } from 'redux';\nimport type { AutoBatchOptions } from './autoBatchEnhancer';\nimport { autoBatchEnhancer } from './autoBatchEnhancer';\nimport { Tuple } from './utils';\nimport type { Middlewares } from './configureStore';\nimport type { ExtractDispatchExtensions } from './tsHelpers';\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions;\n};\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>]>;\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>,>(middlewareEnhancer: StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>): GetDefaultEnhancers<M> => function getDefaultEnhancers(options) {\n  const {\n    autoBatch = true\n  } = options ?? {};\n  let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer);\n  if (autoBatch) {\n    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined));\n  }\n  return enhancerArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Reducer, ReducersMapObject, Middleware, Action, StoreEnhancer, Store, UnknownAction } from 'redux';\nimport { applyMiddleware, createStore, compose, combineReducers, isPlainObject } from './reduxImports';\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';\nimport { composeWithDevTools } from './devtoolsExtension';\nimport type { ThunkMiddlewareFor, GetDefaultMiddleware } from './getDefaultMiddleware';\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware';\nimport type { ExtractDispatchExtensions, ExtractStoreExtensions, ExtractStateExtensions, UnknownIfNonSpecific } from './tsHelpers';\nimport type { Tuple } from './utils';\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers';\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers';\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions;\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean;\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P;\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;\n}\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;\ntype Enhancers = ReadonlyArray<StoreEnhancer>;\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>, StoreEnhancer]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>();\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined\n  } = options || {};\n  let rootReducer: Reducer<S, A, P>;\n  if (typeof reducer === 'function') {\n    rootReducer = reducer;\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>;\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(1) : '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\n  }\n  if (process.env.NODE_ENV !== 'production' && middleware && typeof middleware !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(2) : '`middleware` field must be a callback');\n  }\n  let finalMiddleware: Tuple<Middlewares<S>>;\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware);\n    if (process.env.NODE_ENV !== 'production' && !Array.isArray(finalMiddleware)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(3) : 'when using a middleware builder function, an array of middleware must be returned');\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware();\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(4) : 'each middleware provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>();\n    finalMiddleware.forEach(middleware => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(42) : 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.');\n      }\n      middlewareReferences.add(middleware);\n    });\n  }\n  let finalCompose = compose;\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools)\n    });\n  }\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer);\n  if (process.env.NODE_ENV !== 'production' && enhancers && typeof enhancers !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(5) : '`enhancers` field must be a callback');\n  }\n  let storeEnhancers = typeof enhancers === 'function' ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(6) : '`enhancers` callback must return an array');\n  }\n  if (process.env.NODE_ENV !== 'production' && storeEnhancers.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(7) : 'each enhancer provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n    console.error('middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`');\n  }\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers);\n  return createStore(rootReducer, preloadedState as P, composedEnhancer);\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7 } from \"@reduxjs/toolkit\";\nimport type { Action } from 'redux';\nimport type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';\nimport type { TypeGuard } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk';\nexport type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;\n  rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;\n  fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;\n  settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;\n};\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>;\n  type: Type;\n};\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;\n\n  /**\n   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.\n   * @remarks\n   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param asyncThunk - The async thunk action creator itself.\n   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.\n   * @example\n  ```ts no-transpile\n  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'\n  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {\n  const response = await fetch(`https://reqres.in/api/users/${id}`)\n  return (await response.json()).data\n  })\n  const reducer = createReducer(initialState, (builder) => {\n  builder.addAsyncThunk(fetchUserById, {\n    pending: (state, action) => {\n      state.fetchUserById.loading = 'pending'\n    },\n    fulfilled: (state, action) => {\n      state.fetchUserById.data = action.payload\n    },\n    rejected: (state, action) => {\n      state.fetchUserById.error = action.error\n    },\n    settled: (state, action) => {\n      state.fetchUserById.loading = action.meta.requestStatus\n    },\n  })\n  })\n   */\n  addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n  ```ts\n  import {\n  createAction,\n  createReducer,\n  AsyncThunk,\n  UnknownAction,\n  } from \"@reduxjs/toolkit\";\n  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n  type PendingAction = ReturnType<GenericAsyncThunk[\"pending\"]>;\n  type RejectedAction = ReturnType<GenericAsyncThunk[\"rejected\"]>;\n  type FulfilledAction = ReturnType<GenericAsyncThunk[\"fulfilled\"]>;\n  const initialState: Record<string, string> = {};\n  const resetAction = createAction(\"reset-tracked-loading-state\");\n  function isPendingAction(action: UnknownAction): action is PendingAction {\n  return typeof action.type === \"string\" && action.type.endsWith(\"/pending\");\n  }\n  const reducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(resetAction, () => initialState)\n    // matcher can be defined outside as a type predicate function\n    .addMatcher(isPendingAction, (state, action) => {\n      state[action.meta.requestId] = \"pending\";\n    })\n    .addMatcher(\n      // matcher can be defined inline as a type predicate function\n      (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"rejected\";\n      }\n    )\n    // matcher can just return boolean and the matcher can receive a generic argument\n    .addMatcher<FulfilledAction>(\n      (action) => action.type.endsWith(\"/fulfilled\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"fulfilled\";\n      }\n    );\n  });\n  ```\n   */\n  addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n  ```ts\n  import { createReducer } from '@reduxjs/toolkit'\n  const initialState = { otherActions: 0 }\n  const reducer = createReducer(initialState, builder => {\n  builder\n    // .addCase(...)\n    // .addMatcher(...)\n    .addDefaultCase((state, action) => {\n      state.otherActions++\n    })\n  })\n  ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {};\n}\nexport function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [CaseReducers<S, any>, ActionMatcherDescriptionCollection<S>, CaseReducer<S, Action> | undefined] {\n  const actionsMap: CaseReducers<S, any> = {};\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = [];\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined;\n  const builder = {\n    addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<S>) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(26) : '`builder.addCase` should only be called before calling `builder.addMatcher`');\n        }\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(27) : '`builder.addCase` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n      if (!type) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(28) : '`builder.addCase` cannot be called with an empty action type');\n      }\n      if (type in actionsMap) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(29) : '`builder.addCase` cannot be called with two reducers for the same action type ' + `'${type}'`);\n      }\n      actionsMap[type] = reducer;\n      return builder;\n    },\n    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>) {\n      if (process.env.NODE_ENV !== 'production') {\n        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(43) : '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;\n      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;\n      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;\n      if (reducers.settled) actionMatchers.push({\n        matcher: asyncThunk.settled,\n        reducer: reducers.settled\n      });\n      return builder;\n    },\n    addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<S, A extends Action ? A : A & Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(30) : '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      actionMatchers.push({\n        matcher,\n        reducer\n      });\n      return builder;\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(31) : '`builder.addDefaultCase` can only be called once');\n        }\n      }\n      defaultCaseReducer = reducer;\n      return builder;\n    }\n  };\n  builderCallback(builder);\n  return [actionsMap, actionMatchers, defaultCaseReducer];\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Draft } from 'immer';\nimport { createNextState, isDraft, isDraftable, setUseStrictIteration } from './immerImports';\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { ActionReducerMapBuilder } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { NoInfer, TypeGuard } from './tsHelpers';\nimport { freezeDraftable } from './utils';\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>;\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>;\n  reducer: CaseReducer<S, NoInfer<A>>;\n};\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;\nexport type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void };\nexport type NotFunction<T> = T extends Function ? never : T;\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function';\n}\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S;\n};\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n```ts\nimport {\n  createAction,\n  createReducer,\n  UnknownAction,\n  PayloadAction,\n} from \"@reduxjs/toolkit\";\n\nconst increment = createAction<number>(\"increment\");\nconst decrement = createAction<number>(\"decrement\");\n\nfunction isActionWithNumberPayload(\n  action: UnknownAction\n): action is PayloadAction<number> {\n  return typeof action.payload === \"number\";\n}\n\nconst reducer = createReducer(\n  {\n    counter: 0,\n    sumOfNumberPayloads: 0,\n    unhandledActions: 0,\n  },\n  (builder) => {\n    builder\n      .addCase(increment, (state, action) => {\n        // action is inferred correctly here\n        state.counter += action.payload;\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {\n        state.counter -= action.payload;\n      })\n      // You can apply a \"matcher function\" to incoming actions\n      .addMatcher(isActionWithNumberPayload, (state, action) => {})\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {});\n  }\n);\n```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n    }\n  }\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S;\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState());\n  } else {\n    const frozenInitialState = freezeDraftable(initialState);\n    getInitialState = () => frozenInitialState;\n  }\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n      matcher\n    }) => matcher(action)).map(({\n      reducer\n    }) => reducer)];\n    if (caseReducers.filter(cr => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer];\n    }\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S>; // We can assume this is already a draft\n          const result = caseReducer(draft, action);\n          if (result === undefined) {\n            return previousState;\n          }\n          return result as S;\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action);\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState;\n            }\n            throw Error('A case reducer on a non-draftable value must not return undefined');\n          }\n          return result as S;\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action);\n          });\n        }\n      }\n      return previousState;\n    }, state);\n  }\n  reducer.getInitialState = getInitialState;\n  return reducer as ReducerWithInitialState<S>;\n}","import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action);\n  } else {\n    return matcher(action);\n  }\n};\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]) {\n  if (!action || !action.meta) return false;\n  const hasValidRequestId = typeof action.meta.requestId === 'string';\n  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n  return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return typeof a[0] === 'function' && 'pending' in a[0] && 'fulfilled' in a[0] && 'rejected' in a[0];\n}\nexport type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction;\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.pending));\n}\nexport type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.rejected));\n}\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {\n  rejectValue: infer RejectedValue;\n}> ? {\n  payload: RejectedValue;\n} : unknown);\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue;\n  };\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0]);\n  }\n  return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.fulfilled));\n}\nexport type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;\nexport type AnyAsyncThunk = {\n  pending: {\n    match: (action: any) => action is any;\n  };\n  fulfilled: {\n    match: (action: any) => action is any;\n  };\n  rejected: {\n    match: (action: any) => action is any;\n  };\n};\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}","// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\n/**\n *\n * @public\n */\nexport let nanoid = (size = 21) => {\n  let id = '';\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size;\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[Math.random() * 64 | 0];\n  }\n  return id;\n};","import type { Dispatch, UnknownAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport type { ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport { isAnyOf } from './matchers';\nimport { nanoid } from './nanoid';\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown, SafePromise } from './tsHelpers';\nexport type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {\n  dispatch: D;\n  getState: () => S;\n  extra: E;\n  requestId: string;\n  signal: AbortSignal;\n  abort: (reason?: string) => void;\n  rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;\n  fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;\n};\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string;\n  message?: string;\n  stack?: string;\n  code?: string;\n}\nconst commonProperties: Array<keyof SerializedError> = ['name', 'message', 'stack', 'code'];\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue';\n  constructor(public readonly payload: Payload, public readonly meta: RejectedMeta) {}\n}\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta';\n  constructor(public readonly payload: Payload, public readonly meta: FulfilledMeta) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {};\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property];\n      }\n    }\n    return simpleError;\n  }\n  return {\n    message: String(value)\n  };\n};\nexport type AsyncThunkConfig = {\n  state?: unknown;\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;\n  extra?: unknown;\n  rejectValue?: unknown;\n  serializedErrorType?: unknown;\n  pendingMeta?: unknown;\n  fulfilledMeta?: unknown;\n  rejectedMeta?: unknown;\n};\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State;\n} ? State : unknown;\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends {\n  extra: infer Extra;\n} ? Extra : unknown;\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch;\n} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue;\n} ? RejectValue : unknown;\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta;\n} ? PendingMeta : unknown;\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta;\n} ? FulfilledMeta : unknown;\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta;\n} ? RejectedMeta : unknown;\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType;\n} ? GetSerializedErrorType : SerializedError;\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {\n  abort: (reason?: string) => void;\n  requestId: string;\n  arg: ThunkArg;\n  unwrap: () => Promise<Returned>;\n};\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal;\n}\ntype AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg,\n// any handling\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// unknown handling\nunknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n: [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n: [void] extends [ThunkArg] // make optional\n? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n: [undefined] extends [ThunkArg] ? WithStrictNullChecks<\n// with strict nullChecks: make optional\n(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// without strict null checks this will match everything, so don't make it optional\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> // default case: normal argument\n: (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean;\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string;\n} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   *\n   * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n   * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n   */\n  getPendingMeta?(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   */\n  getPendingMeta(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}>;\nexport type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?], undefined, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'pending';\n} & GetPendingMeta<ThunkApiConfig>>;\nexport type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Error | null, string, ThunkArg, GetRejectValue<ThunkApiConfig>?, GetRejectedMeta<ThunkApiConfig>?], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'rejected';\n  aborted: boolean;\n  condition: boolean;\n} & (({\n  rejectedWithValue: false;\n} & { [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined }) | ({\n  rejectedWithValue: true;\n} & GetRejectedMeta<ThunkApiConfig>))>;\nexport type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?], Returned, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'fulfilled';\n} & GetFulfilledMeta<ThunkApiConfig>>;\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;\n  fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;\n  // matchSettled?\n  settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;\n  typePrefix: string;\n};\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;\nexport type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n  withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\nconst externalAbortMessage = 'External signal was aborted';\nexport const createAsyncThunk = /* @__PURE__ */(() => {\n  function createAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>;\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>;\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>;\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>;\n    const fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/fulfilled', (payload: Returned, requestId: string, arg: ThunkArg, meta?: FulfilledMeta) => ({\n      payload,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'fulfilled' as const\n      }\n    }));\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/pending', (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n      payload: undefined,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'pending' as const\n      }\n    }));\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/rejected', (error: Error | null, requestId: string, arg: ThunkArg, payload?: RejectedValue, meta?: RejectedMeta) => ({\n      payload,\n      error: (options && options.serializeError || miniSerializeError)(error || 'Rejected') as GetSerializedErrorType<ThunkApiConfig>,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        rejectedWithValue: !!payload,\n        requestStatus: 'rejected' as const,\n        aborted: error?.name === 'AbortError',\n        condition: error?.name === 'ConditionError'\n      }\n    }));\n    function actionCreator(arg: ThunkArg, {\n      signal\n    }: AsyncThunkDispatchConfig = {}): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n        const abortController = new AbortController();\n        let abortHandler: (() => void) | undefined;\n        let abortReason: string | undefined;\n        function abort(reason?: string) {\n          abortReason = reason;\n          abortController.abort();\n        }\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage);\n          } else {\n            signal.addEventListener('abort', () => abort(externalAbortMessage), {\n              once: true\n            });\n          }\n        }\n        const promise = async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>;\n          try {\n            let conditionResult = options?.condition?.(arg, {\n              getState,\n              extra\n            });\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult;\n            }\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.'\n              };\n            }\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted'\n                });\n              };\n              abortController.signal.addEventListener('abort', abortHandler, {\n                once: true\n              });\n            });\n            dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n              requestId,\n              arg\n            }, {\n              getState,\n              extra\n            })) as any);\n            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n              dispatch,\n              getState,\n              extra,\n              requestId,\n              signal: abortController.signal,\n              abort,\n              rejectWithValue: ((value: RejectedValue, meta?: RejectedMeta) => {\n                return new RejectWithValue(value, meta);\n              }) as any,\n              fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                return new FulfillWithMeta(value, meta);\n              }) as any\n            })).then(result => {\n              if (result instanceof RejectWithValue) {\n                throw result;\n              }\n              if (result instanceof FulfillWithMeta) {\n                return fulfilled(result.payload, requestId, arg, result.meta);\n              }\n              return fulfilled(result as any, requestId, arg);\n            })]);\n          } catch (err) {\n            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err as any, requestId, arg);\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler);\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && (finalAction as any).meta.condition;\n          if (!skipDispatch) {\n            dispatch(finalAction as any);\n          }\n          return finalAction;\n        }();\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult);\n          }\n        });\n      };\n    }\n    return Object.assign(actionCreator as AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig>, {\n      pending,\n      rejected,\n      fulfilled,\n      settled: isAnyOf(rejected, fulfilled),\n      typePrefix\n    });\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk;\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>;\n})();\ninterface UnwrappableAction {\n  payload: any;\n  meta?: any;\n  error?: any;\n}\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {\n  error: any;\n}>['payload'];\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload;\n  }\n  if (action.error) {\n    throw action.error;\n  }\n  return action.payload;\n}\ntype WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return value !== null && typeof value === 'object' && typeof value.then === 'function';\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { Selector } from 'reselect';\nimport type { InjectConfig } from './combineSlices';\nimport type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport type { AsyncThunk, AsyncThunkConfig, AsyncThunkOptions, AsyncThunkPayloadCreator, OverrideThunkApiConfigs } from './createAsyncThunk';\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk';\nimport type { ActionMatcherDescriptionCollection, CaseReducer, ReducerWithInitialState } from './createReducer';\nimport { createReducer } from './createReducer';\nimport type { ActionReducerMapBuilder, AsyncThunkReducers, TypedActionCreator } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { Id, TypeGuard } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\nconst asyncThunkSymbol = /* @__PURE__ */Symbol.for('rtk-slice-createasyncthunk');\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk;\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk\n};\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath;\n};\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice name.\n   */\n  name: Name;\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath;\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>;\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>;\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>;\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State;\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>>;\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {\n    inject: (slice: {\n      reducerPath: string;\n      reducer: Reducer;\n    }, config?: InjectConfig) => void;\n  }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State;\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]?: State | undefined }>>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State;\n};\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name;\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath;\n\n  /**\n   * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n   */\n  initialState: State | (() => State);\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n  ```ts\n  import { createAction, createSlice, Action } from '@reduxjs/toolkit'\n  const incrementBy = createAction<number>('incrementBy')\n  const decrement = createAction('decrement')\n  interface RejectedAction extends Action {\n  error: Error\n  }\n  function isRejectedAction(action: Action): action is RejectedAction {\n  return action.type.endsWith('rejected')\n  }\n  createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {},\n  extraReducers: builder => {\n    builder\n      .addCase(incrementBy, (state, action) => {\n        // action is inferred correctly here if using TS\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {})\n      // You can match a range of action types\n      .addMatcher(\n        isRejectedAction,\n        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n        (state, action) => {}\n      )\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {})\n    }\n  })\n  ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors;\n}\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T;\n};\nexport type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>;\n  prepare: PrepareAction<Action['payload']>;\n};\nexport interface CaseReducerWithPrepareDefinition<State, Action extends PayloadAction> extends CaseReducerWithPrepare<State, Action>, ReducerDefinition<ReducerType.reducerWithPrepare> {}\ntype AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;\n};\ntype AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;\n};\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = { [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K] };\ninterface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {\n  <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;\n  <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;\n  withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n}\nexport interface ReducerCreators<State> {\n  reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;\n  reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;\n  asyncThunk: AsyncThunkCreator<State>;\n  preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare;\n    prepare: Prepare;\n    reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;\n  };\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any;\n};\ntype SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {\n  prepare: any;\n} ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {\n  reducer: any;\n} ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never };\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<CR extends {\n  prepare: any;\n}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ((state: any, action: infer Action) => any) ? Action extends {\n  payload: infer P;\n} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {\n  reducer: infer Reducer;\n} ? Reducer : Definition : never };\ntype RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {\n  unwrapped: S;\n} : never;\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState> };\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends {\n  reducer(s: S, action?: infer A): any;\n} ? {\n  prepare(...a: never[]): Omit<A, 'type'>;\n} : {} };\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`;\n}\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator;\n  };\n}\nexport function buildCreateSlice({\n  creators\n}: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n  return function createSlice<State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {\n    const {\n      name,\n      reducerPath = name as unknown as ReducerPath\n    } = options;\n    if (!name) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(11) : '`name` is a required option for createSlice');\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (options.initialState === undefined) {\n        console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`');\n      }\n    }\n    const reducers = (typeof options.reducers === 'function' ? options.reducers(buildReducerCreators<State>()) : options.reducers) || {};\n    const reducerNames = Object.keys(reducers);\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: []\n    };\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<State>) {\n        const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n        if (!type) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(12) : '`context.addCase` cannot be called with an empty action type');\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(13) : '`context.addCase` cannot be called with two reducers for the same action type: ' + type);\n        }\n        context.sliceCaseReducersByType[type] = reducer;\n        return contextMethods;\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({\n          matcher,\n          reducer\n        });\n        return contextMethods;\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator;\n        return contextMethods;\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer;\n        return contextMethods;\n      }\n    };\n    reducerNames.forEach(reducerName => {\n      const reducerDefinition = reducers[reducerName];\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function'\n      };\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n      } else {\n        handleNormalReducerDefinition<State>(reducerDetails, reducerDefinition as any, contextMethods);\n      }\n    });\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n        }\n      }\n      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = undefined] = typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType\n      };\n      return createReducer(options.initialState, builder => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>);\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer);\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer);\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer);\n        }\n      });\n    }\n    const selectSelf = (state: State) => state;\n    const injectedSelectorCache = new Map<boolean, WeakMap<(rootState: any) => State | undefined, Record<string, (rootState: any) => any>>>();\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>();\n    let _reducer: ReducerWithInitialState<State>;\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer(state, action);\n    }\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer.getInitialState();\n    }\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(reducerPath: CurrentReducerPath, injected = false): Pick<Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'> {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath];\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(15) : 'selectSlice returned undefined for an uninjected slice reducer');\n          }\n        }\n        return sliceState;\n      }\n      function getSelectors(selectState: (rootState: any) => State = selectSelf) {\n        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => new WeakMap());\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {};\n          for (const [name, selector] of Object.entries(options.selectors ?? {})) {\n            map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);\n          }\n          return map;\n        }) as any;\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice);\n        },\n        selectSlice\n      };\n    }\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, {\n        reducerPath: pathOpt,\n        ...config\n      } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath;\n        injectable.inject({\n          reducerPath: newReducerPath,\n          reducer\n        }, config);\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true)\n        } as any;\n      }\n    };\n    return slice;\n  };\n}\nfunction wrapSelector<State, NewState, S extends Selector<State>>(selector: S, selectState: Selector<NewState, State>, getInitialState: () => State, injected?: boolean) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState);\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState();\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(16) : 'selectState returned undefined for an uninjected slice reducer');\n      }\n    }\n    return selector(sliceState, ...args);\n  }\n  wrapper.unwrapped = selector;\n  return wrapper as RemappedSelector<S, NewState>;\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */buildCreateSlice();\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<string, CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>>;\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>;\n  sliceMatchers: ActionMatcherDescriptionCollection<State>;\n  actionCreators: Record<string, Function>;\n}\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ReducerHandlingContextMethods<State>;\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ReducerHandlingContextMethods<State>;\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<State, A extends Action ? A : A & Action>): ReducerHandlingContextMethods<State>;\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * context.exposeAction(\"addPost\", createAction<Post>(\"addPost\"));\n   *\n   * export const { addPost } = slice.actions\n   *\n   * dispatch(addPost(post))\n   */\n  exposeAction(name: string, actionCreator: Function): ReducerHandlingContextMethods<State>;\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * context.exposeCaseReducer(\"addPost\", (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload)\n   * })\n   *\n   * slice.caseReducers.addPost([], addPost(post))\n   */\n  exposeCaseReducer(name: string, reducer: CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>): ReducerHandlingContextMethods<State>;\n}\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string;\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string;\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean;\n}\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(payloadCreator: AsyncThunkPayloadCreator<any, any>, config: AsyncThunkSliceReducerConfig<State, any>): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config\n    };\n  }\n  asyncThunk.withTypes = () => asyncThunk;\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign({\n        // hack so the wrapping function has the same name as the original\n        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n        [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n          return caseReducer(...args);\n        }\n      }[caseReducer.name], {\n        _reducerDefinitionType: ReducerType.reducer\n      } as const);\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer\n      };\n    },\n    asyncThunk: asyncThunk as any\n  };\n}\nfunction handleNormalReducerDefinition<State>({\n  type,\n  reducerName,\n  createNotation\n}: ReducerDetails, maybeReducerWithPrepare: CaseReducer<State, {\n  payload: any;\n  type: string;\n}> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, context: ReducerHandlingContextMethods<State>) {\n  let caseReducer: CaseReducer<State, any>;\n  let prepareCallback: PrepareAction<any> | undefined;\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(17) : 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.');\n    }\n    caseReducer = maybeReducerWithPrepare.reducer;\n    prepareCallback = maybeReducerWithPrepare.prepare;\n  } else {\n    caseReducer = maybeReducerWithPrepare;\n  }\n  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition<State>(reducerDefinition: any): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk;\n}\nfunction isCaseReducerWithPrepareDefinition<State>(reducerDefinition: any): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare;\n}\nfunction handleThunkCaseReducerDefinition<State>({\n  type,\n  reducerName\n}: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, context: ReducerHandlingContextMethods<State>, cAT: typeof _createAsyncThunk | undefined) {\n  if (!cAT) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(18) : 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.');\n  }\n  const {\n    payloadCreator,\n    fulfilled,\n    pending,\n    rejected,\n    settled,\n    options\n  } = reducerDefinition;\n  const thunk = cAT(type, payloadCreator, options as any);\n  context.exposeAction(reducerName, thunk);\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled);\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending);\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected);\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled);\n  }\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop\n  });\n}\nfunction noop() {}","import type { EntityId, EntityState, EntityStateAdapter, EntityStateFactory } from './models';\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<T, Id> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>\n  };\n}\nexport function createInitialStateFactory<T, Id extends EntityId>(stateAdapter: EntityStateAdapter<T, Id>): EntityStateFactory<T, Id> {\n  function getInitialState(state?: undefined, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id>;\n  function getInitialState<S extends object>(additionalState: S, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id> & S;\n  function getInitialState(additionalState: any = {}, entities?: readonly T[] | Record<Id, T>): any {\n    const state = Object.assign(getInitialEntityState(), additionalState);\n    return entities ? stateAdapter.setAll(state, entities) : state;\n  }\n  return {\n    getInitialState\n  };\n}","import type { CreateSelectorFunction, Selector } from 'reselect';\nimport { createDraftSafeSelector } from '../createDraftSafeSelector';\nimport type { EntityId, EntitySelectors, EntityState } from './models';\ntype AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction;\n};\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;\n  function getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;\n  function getSelectors<V>(selectState?: (state: V) => EntityState<T, Id>, options: GetSelectorsOptions = {}): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction\n    } = options;\n    const selectIds = (state: EntityState<T, Id>) => state.ids;\n    const selectEntities = (state: EntityState<T, Id>) => state.entities;\n    const selectAll = createSelector(selectIds, selectEntities, (ids, entities): T[] => ids.map(id => entities[id]!));\n    const selectId = (_: unknown, id: Id) => id;\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id];\n    const selectTotal = createSelector(selectIds, ids => ids.length);\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById)\n      };\n    }\n    const selectGlobalizedEntities = createSelector(selectState as Selector<V, EntityState<T, Id>>, selectEntities);\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(selectGlobalizedEntities, selectId, selectById)\n    };\n  }\n  return {\n    getSelectors\n  };\n}","import { createNextState, isDraft } from '../immerImports';\nimport type { Draft } from 'immer';\nimport type { EntityId, DraftableEntityState, PreventAny } from './models';\nimport type { PayloadAction } from '../createAction';\nimport { isFSA } from '../createAction';\nexport const isDraftTyped = isDraft as <T>(value: T | Draft<T>) => value is Draft<T>;\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(mutator: (state: DraftableEntityState<T, Id>) => void) {\n  const operator = createStateOperator((_: undefined, state: DraftableEntityState<T, Id>) => mutator(state));\n  return function operation<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S {\n    return operator(state as S, undefined);\n  };\n}\nexport function createStateOperator<T, Id extends EntityId, R>(mutator: (arg: R, state: DraftableEntityState<T, Id>) => void) {\n  return function operation<S extends DraftableEntityState<T, Id>>(state: S, arg: R | PayloadAction<R>): S {\n    function isPayloadActionArgument(arg: R | PayloadAction<R>): arg is PayloadAction<R> {\n      return isFSA(arg);\n    }\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft);\n      } else {\n        mutator(arg, draft);\n      }\n    };\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state);\n\n      // since it's a draft, we'll just return it\n      return state;\n    }\n    return createNextState(state, runMutator);\n  };\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../immerImports';\nimport type { DraftableEntityState, EntityId, IdSelector, Update } from './models';\nexport function selectIdValue<T, Id extends EntityId>(entity: T, selectId: IdSelector<T, Id>) {\n  const key = selectId(entity);\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    console.warn('The entity passed to the `selectId` implementation returned undefined.', 'You should probably provide your own `selectId` implementation.', 'The entity that was passed:', entity, 'The `selectId` implementation:', selectId.toString());\n  }\n  return key;\n}\nexport function ensureEntitiesArray<T, Id extends EntityId>(entities: readonly T[] | Record<Id, T>): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities);\n  }\n  return entities;\n}\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}\nexport function splitAddedUpdatedEntities<T, Id extends EntityId>(newEntities: readonly T[] | Record<Id, T>, selectId: IdSelector<T, Id>, state: DraftableEntityState<T, Id>): [T[], Update<T, Id>[], Id[]] {\n  newEntities = ensureEntitiesArray(newEntities);\n  const existingIdsArray = getCurrent(state.ids);\n  const existingIds = new Set<Id>(existingIdsArray);\n  const added: T[] = [];\n  const addedIds = new Set<Id>([]);\n  const updated: Update<T, Id>[] = [];\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId);\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({\n        id,\n        changes: entity\n      });\n    } else {\n      addedIds.add(id);\n      added.push(entity);\n    }\n  }\n  return [added, updated, existingIdsArray];\n}","import type { Draft } from 'immer';\nimport type { EntityStateAdapter, IdSelector, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator, createSingleArgumentStateOperator } from './state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities } from './utils';\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (key in state.entities) {\n      return;\n    }\n    state.ids.push(key as Id & Draft<Id>);\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      addOneMutably(entity, state);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>);\n    }\n    ;\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      setOneMutably(entity, state);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.ids = [];\n    state.entities = {} as Record<Id, T>;\n    addManyMutably(newEntities, state);\n  }\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state);\n  }\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false;\n    keys.forEach(key => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key];\n        didMutate = true;\n      }\n    });\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter(id => id in state.entities) as Id[] | Draft<Id[]>;\n    }\n  }\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {}\n    });\n  }\n  function takeNewKey(keys: {\n    [id: string]: Id;\n  }, update: Update<T, Id>, state: R): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id];\n    if (original === undefined) {\n      return false;\n    }\n    const updated: T = Object.assign({}, original, update.changes);\n    const newKey = selectIdValue(updated, selectId);\n    const hasNewKey = newKey !== update.id;\n    if (hasNewKey) {\n      keys[update.id] = newKey;\n      delete (state.entities as Record<Id, T>)[update.id];\n    }\n    ;\n    (state.entities as Record<Id, T>)[newKey] = updated;\n    return hasNewKey;\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    const newKeys: {\n      [id: string]: Id;\n    } = {};\n    const updatesPerEntity: {\n      [id: string]: Update<T, Id>;\n    } = {};\n    updates.forEach(update => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes\n          }\n        };\n      }\n    });\n    updates = Object.values(updatesPerEntity);\n    const didMutateEntities = updates.length > 0;\n    if (didMutateEntities) {\n      const didMutateIds = updates.filter(update => takeNewKey(newKeys, update, state)).length > 0;\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map(e => selectIdValue(e as T, selectId));\n      }\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    addManyMutably(added, state);\n    updateManyMutably(updated, state);\n  }\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably)\n  };\n}","import type { IdSelector, Comparer, EntityStateAdapter, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator } from './state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities, getCurrent } from './utils';\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): number {\n  let lowIndex = 0;\n  let highIndex = sortedItems.length;\n  while (lowIndex < highIndex) {\n    let middleIndex = lowIndex + highIndex >>> 1;\n    const currentItem = sortedItems[middleIndex];\n    const res = comparisonFunction(item, currentItem);\n    if (res >= 0) {\n      lowIndex = middleIndex + 1;\n    } else {\n      highIndex = middleIndex;\n    }\n  }\n  return lowIndex;\n}\nexport function insert<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n  sortedItems.splice(insertAtIndex, 0, item);\n  return sortedItems;\n}\nexport function createSortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>, comparer: Comparer<T>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  const {\n    removeOne,\n    removeMany,\n    removeAll\n  } = createUnsortedStateAdapter(selectId);\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state);\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R, existingIds?: Id[]): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids));\n    const addedKeys = new Set<Id>();\n    const models = newEntities.filter(model => {\n      const modelId = selectIdValue(model, selectId);\n      const notAdded = !addedKeys.has(modelId);\n      if (notAdded) addedKeys.add(modelId);\n      return !existingKeys.has(modelId) && notAdded;\n    });\n    if (models.length !== 0) {\n      mergeFunction(state, models);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state);\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    let deduplicatedEntities = {} as Record<Id, T>;\n    newEntities = ensureEntitiesArray(newEntities);\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        const entityId = selectId(item);\n        // For multiple items with the same ID, we should keep the last one.\n        deduplicatedEntities[entityId] = item;\n        delete (state.entities as Record<Id, T>)[entityId];\n      }\n      newEntities = ensureEntitiesArray(deduplicatedEntities);\n      mergeFunction(state, newEntities);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.entities = {} as Record<Id, T>;\n    state.ids = [];\n    addManyMutably(newEntities, state, []);\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    let appliedUpdates = false;\n    let replacedIds = false;\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id];\n      if (!entity) {\n        continue;\n      }\n      appliedUpdates = true;\n      Object.assign(entity, update.changes);\n      const newId = selectId(entity);\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true;\n        delete (state.entities as Record<Id, T>)[update.id];\n        const oldIndex = (state.ids as Id[]).indexOf(update.id);\n        state.ids[oldIndex] = newId;\n        (state.entities as Record<Id, T>)[newId] = entity;\n      }\n    }\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds);\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray);\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state);\n    }\n  }\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue;\n      }\n      return false;\n    }\n    return true;\n  }\n  type MergeFunction = (state: R, addedItems: readonly T[], appliedUpdates?: boolean, replacedIds?: boolean) => void;\n  const mergeFunction: MergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n    const currentEntities = getCurrent(state.entities);\n    const currentIds = getCurrent(state.ids);\n    const stateEntities = state.entities as Record<Id, T>;\n    let ids: Iterable<Id> = currentIds;\n    if (replacedIds) {\n      ids = new Set(currentIds);\n    }\n    let sortedEntities: T[] = [];\n    for (const id of ids) {\n      const entity = currentEntities[id];\n      if (entity) {\n        sortedEntities.push(entity);\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0;\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item;\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer);\n      }\n    }\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer);\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer);\n    }\n    const newSortedIds = sortedEntities.map(selectId);\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds;\n    }\n  };\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably)\n  };\n}","import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models';\nimport { createInitialStateFactory } from './entity_state';\nimport { createSelectorsFactory } from './state_selectors';\nimport { createSortedStateAdapter } from './sorted_state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport type { WithRequiredProp } from '../tsHelpers';\nexport function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;\nexport function createEntityAdapter<T extends {\n  id: EntityId;\n}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(options: EntityAdapterOptions<T, EntityId> = {}): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options\n  };\n  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n  const stateFactory = createInitialStateFactory(stateAdapter);\n  const selectorsFactory = createSelectorsFactory<T, EntityId>();\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter\n  };\n}","import type { SerializedError } from '@reduxjs/toolkit';\nconst task = 'task';\nconst listener = 'listener';\nconst completed = 'completed';\nconst cancelled = 'cancelled';\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const;\nexport const taskCompleted = `task-${completed}` as const;\nexport const listenerCancelled = `${listener}-${cancelled}` as const;\nexport const listenerCompleted = `${listener}-${completed}` as const;\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError';\n  message: string;\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nexport const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown = (func: unknown, expected: string) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(32) : `${expected} is not a function`);\n  }\n};\nexport const noop = () => {};\nexport const catchRejection = <T,>(promise: Promise<T>, onError = noop): Promise<T> => {\n  promise.catch(onError);\n  return promise;\n};\nexport const addAbortSignalListener = (abortSignal: AbortSignal, callback: (evt: Event) => void) => {\n  abortSignal.addEventListener('abort', callback, {\n    once: true\n  });\n  return () => abortSignal.removeEventListener('abort', callback);\n};","import { TaskAbortError } from './exceptions';\nimport type { TaskResult } from './types';\nimport { addAbortSignalListener, catchRejection, noop } from './utils';\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @see {TaskAbortError}\n * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    throw new TaskAbortError(signal.reason);\n  }\n};\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(signal: AbortSignal, promise: Promise<T>): Promise<T> {\n  let cleanup = noop;\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n    if (signal.aborted) {\n      notifyRejection();\n      return;\n    }\n    cleanup = addAbortSignalListener(signal, notifyRejection);\n    promise.finally(() => cleanup()).then(resolve, reject);\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop;\n  });\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T,>(task: () => Promise<T>, cleanUp?: () => void): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve();\n    const value = await task();\n    return {\n      status: 'ok',\n      value\n    };\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error\n    };\n  } finally {\n    cleanUp?.();\n  }\n};\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T,>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(raceWithSignal(signal, promise).then(output => {\n      validateActive(signal);\n      return output;\n    }));\n  };\n};\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal);\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>(resolve => setTimeout(resolve, timeoutMs)));\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux';\nimport { isAction } from '../reduxImports';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport { createAction } from '../createAction';\nimport { nanoid } from '../nanoid';\nimport { TaskAbortError, listenerCancelled, listenerCompleted, taskCancelled, taskCompleted } from './exceptions';\nimport { createDelay, createPause, raceWithSignal, runTask, validateActive } from './task';\nimport type { AddListenerOverloads, AnyListenerPredicate, CreateListenerMiddlewareOptions, FallbackAddListenerOptions, ForkOptions, ForkedTask, ForkedTaskExecutor, ListenerEntry, ListenerErrorHandler, ListenerErrorInfo, ListenerMiddleware, ListenerMiddlewareInstance, TakePattern, TaskResult, TypedAddListener, TypedCreateListenerEntry, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\nimport { addAbortSignalListener, assertFunction, catchRejection, noop } from './utils';\nexport { TaskAbortError } from './exceptions';\nexport type { AsyncTaskExecutor, CreateListenerMiddlewareOptions, ForkedTask, ForkedTaskAPI, ForkedTaskExecutor, ListenerEffect, ListenerEffectAPI, ListenerErrorHandler, ListenerMiddleware, ListenerMiddlewareInstance, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, TypedAddListener, TypedRemoveListener, TypedStartListening, TypedStopListening, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\n\n//Overly-aggressive byte-shaving\nconst {\n  assign\n} = Object;\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const;\nconst alm = 'listenerMiddleware' as const;\nconst createFork = (parentAbortSignal: AbortSignal, parentBlockingPromises: Promise<any>[]) => {\n  const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));\n  return <T,>(taskExecutor: ForkedTaskExecutor<T>, opts?: ForkOptions): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor');\n    const childAbortController = new AbortController();\n    linkControllers(childAbortController);\n    const result = runTask<T>(async (): Promise<T> => {\n      validateActive(parentAbortSignal);\n      validateActive(childAbortController.signal);\n      const result = (await taskExecutor({\n        pause: createPause(childAbortController.signal),\n        delay: createDelay(childAbortController.signal),\n        signal: childAbortController.signal\n      })) as T;\n      validateActive(childAbortController.signal);\n      return result;\n    }, () => childAbortController.abort(taskCompleted));\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop));\n    }\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        childAbortController.abort(taskCancelled);\n      }\n    };\n  };\n};\nconst createTakePattern = <S,>(startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>, signal: AbortSignal): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>,>(predicate: P, timeout: number | undefined) => {\n    validateActive(signal);\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {};\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe();\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n        }\n      });\n      unsubscribe = () => {\n        stopListening();\n        reject();\n      };\n    });\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise];\n    if (timeout != null) {\n      promises.push(new Promise<null>(resolve => setTimeout(resolve, timeout, null)));\n    }\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises));\n      validateActive(signal);\n      return output;\n    } finally {\n      // Always clean up the listener\n      unsubscribe();\n    }\n  };\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) => catchRejection(take(predicate, timeout))) as TakePattern<S>;\n};\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let {\n    type,\n    actionCreator,\n    matcher,\n    predicate,\n    effect\n  } = options;\n  if (type) {\n    predicate = createAction(type).match;\n  } else if (actionCreator) {\n    type = actionCreator!.type;\n    predicate = actionCreator.match;\n  } else if (matcher) {\n    predicate = matcher;\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(21) : 'Creating or removing a listener requires one of the known fields for matching an action');\n  }\n  assertFunction(effect, 'options.listener');\n  return {\n    predicate,\n    type,\n    effect\n  };\n};\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> = /* @__PURE__ */assign((options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    predicate,\n    effect\n  } = getListenerEntryPropsFrom(options);\n  const entry: ListenerEntry<unknown> = {\n    id: nanoid(),\n    effect,\n    type,\n    predicate,\n    pending: new Set<AbortController>(),\n    unsubscribe: () => {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(22) : 'Unsubscribe not initialized');\n    }\n  };\n  return entry;\n}, {\n  withTypes: () => createListenerEntry\n}) as unknown as TypedCreateListenerEntry<unknown>;\nconst findListenerEntry = (listenerMap: Map<string, ListenerEntry>, options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    effect,\n    predicate\n  } = getListenerEntryPropsFrom(options);\n  return Array.from(listenerMap.values()).find(entry => {\n    const matchPredicateOrType = typeof type === 'string' ? entry.type === type : entry.predicate === predicate;\n    return matchPredicateOrType && entry.effect === effect;\n  });\n};\nconst cancelActiveListeners = (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>) => {\n  entry.pending.forEach(controller => {\n    controller.abort(listenerCancelled);\n  });\n};\nconst createClearListenerMiddleware = (listenerMap: Map<string, ListenerEntry>, executingListeners: Map<ListenerEntry, number>) => {\n  return () => {\n    for (const listener of executingListeners.keys()) {\n      cancelActiveListeners(listener);\n    }\n    listenerMap.clear();\n  };\n};\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (errorHandler: ListenerErrorHandler, errorToNotify: unknown, errorInfo: ListenerErrorInfo): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo);\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError;\n    }, 0);\n  }\n};\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/add`), {\n  withTypes: () => addListener\n}) as unknown as TypedAddListener<unknown>;\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */createAction(`${alm}/removeAll`);\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/remove`), {\n  withTypes: () => removeListener\n}) as unknown as TypedRemoveListener<unknown>;\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args);\n};\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {}) => {\n  const listenerMap = new Map<string, ListenerEntry>();\n\n  // Track listeners whose effect is currently executing so clearListeners can\n  // abort even listeners that have become unsubscribed while executing.\n  const executingListeners = new Map<ListenerEntry, number>();\n  const trackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 0;\n    executingListeners.set(entry, count + 1);\n  };\n  const untrackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 1;\n    if (count === 1) {\n      executingListeners.delete(entry);\n    } else {\n      executingListeners.set(entry, count - 1);\n    }\n  };\n  const {\n    extra,\n    onError = defaultErrorHandler\n  } = middlewareOptions;\n  assertFunction(onError, 'onError');\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id);\n    listenerMap.set(entry.id, entry);\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe();\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    };\n  };\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options as any);\n    return insertEntry(entry);\n  }) as AddListenerOverloads<any>;\n  assign(startListening, {\n    withTypes: () => startListening\n  });\n  const stopListening = (options: FallbackAddListenerOptions & UnsubscribeListenerOptions): boolean => {\n    const entry = findListenerEntry(listenerMap, options);\n    if (entry) {\n      entry.unsubscribe();\n      if (options.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    }\n    return !!entry;\n  };\n  assign(stopListening, {\n    withTypes: () => stopListening\n  });\n  const notifyListener = async (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>, action: unknown, api: MiddlewareAPI, getOriginalState: () => StateType) => {\n    const internalTaskController = new AbortController();\n    const take = createTakePattern(startListening as AddListenerOverloads<any>, internalTaskController.signal);\n    const autoJoinPromises: Promise<any>[] = [];\n    try {\n      entry.pending.add(internalTaskController);\n      trackExecutingListener(entry);\n      await Promise.resolve(entry.effect(action,\n      // Use assign() rather than ... to avoid extra helper functions added to bundle\n      assign({}, api, {\n        getOriginalState,\n        condition: (predicate: AnyListenerPredicate<any>, timeout?: number) => take(predicate, timeout).then(Boolean),\n        take,\n        delay: createDelay(internalTaskController.signal),\n        pause: createPause<any>(internalTaskController.signal),\n        extra,\n        signal: internalTaskController.signal,\n        fork: createFork(internalTaskController.signal, autoJoinPromises),\n        unsubscribe: entry.unsubscribe,\n        subscribe: () => {\n          listenerMap.set(entry.id, entry);\n        },\n        cancelActiveListeners: () => {\n          entry.pending.forEach((controller, _, set) => {\n            if (controller !== internalTaskController) {\n              controller.abort(listenerCancelled);\n              set.delete(controller);\n            }\n          });\n        },\n        cancel: () => {\n          internalTaskController.abort(listenerCancelled);\n          entry.pending.delete(internalTaskController);\n        },\n        throwIfCancelled: () => {\n          validateActive(internalTaskController.signal);\n        }\n      })));\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect'\n        });\n      }\n    } finally {\n      await Promise.all(autoJoinPromises);\n      internalTaskController.abort(listenerCompleted); // Notify that the task has completed\n      untrackExecutingListener(entry);\n      entry.pending.delete(internalTaskController);\n    }\n  };\n  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);\n  const middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument> = api => next => action => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action);\n    }\n    if (addListener.match(action)) {\n      return startListening(action.payload as any);\n    }\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware();\n      return;\n    }\n    if (removeListener.match(action)) {\n      return stopListening(action.payload);\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState();\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);\n      }\n      return originalState as StateType;\n    };\n    let result: unknown;\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action);\n      if (listenerMap.size > 0) {\n        const currentState = api.getState();\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values());\n        for (const entry of listenerEntries) {\n          let runListener = false;\n          try {\n            runListener = entry.predicate(action, currentState, originalState);\n          } catch (predicateError) {\n            runListener = false;\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate'\n            });\n          }\n          if (!runListener) {\n            continue;\n          }\n          notifyListener(entry, action, api, getOriginalState);\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN;\n    }\n    return result;\n  };\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;\n};","import type { Dispatch, Middleware, UnknownAction } from 'redux';\nimport { compose } from '../reduxImports';\nimport { createAction } from '../createAction';\nimport { isAllOf } from '../matchers';\nimport { nanoid } from '../nanoid';\nimport { getOrInsertComputed } from '../utils';\nimport type { AddMiddleware, DynamicMiddleware, DynamicMiddlewareInstance, MiddlewareEntry, WithMiddleware } from './types';\nexport type { DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './types';\nconst createMiddlewareEntry = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(middleware: Middleware<any, State, DispatchType>): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map()\n});\nconst matchInstance = (instanceId: string) => (action: any): action is {\n  meta: {\n    instanceId: string;\n  };\n} => action?.meta?.instanceId === instanceId;\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid();\n  const middlewareMap = new Map<Middleware<any, State, DispatchType>, MiddlewareEntry<State, DispatchType>>();\n  const withMiddleware = Object.assign(createAction('dynamicMiddleware/add', (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n    payload: middlewares,\n    meta: {\n      instanceId\n    }\n  })), {\n    withTypes: () => withMiddleware\n  }) as WithMiddleware<State, DispatchType>;\n  const addMiddleware = Object.assign(function addMiddleware(...middlewares: Middleware<any, State, DispatchType>[]) {\n    middlewares.forEach(middleware => {\n      getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);\n    });\n  }, {\n    withTypes: () => addMiddleware\n  }) as AddMiddleware<State, DispatchType>;\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = api => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map(entry => getOrInsertComputed(entry.applied, api, entry.middleware));\n    return compose(...appliedMiddleware);\n  };\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n  const middleware: DynamicMiddleware<State, DispatchType> = api => next => action => {\n    if (isWithMiddleware(action)) {\n      addMiddleware(...action.payload);\n      return api.dispatch;\n    }\n    return getFinalMiddleware(api)(next)(action);\n  };\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { PreloadedStateShapeFromReducersMapObject, Reducer, StateFromReducersMapObject, UnknownAction } from 'redux';\nimport { combineReducers } from 'redux';\nimport { nanoid } from './nanoid';\nimport type { Id, NonUndefined, Tail, UnionToIntersection, WithOptionalProp } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\ntype SliceLike<ReducerPath extends string, State, PreloadedState = State> = {\n  reducerPath: ReducerPath;\n  reducer: Reducer<State, any, PreloadedState>;\n};\ntype AnySliceLike = SliceLike<string, any>;\ntype SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;\ntype SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;\ntype SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;\nexport type WithSlice<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikeState<A> };\nexport type WithSlicePreloadedState<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A> };\ntype ReducerMap = Record<string, Reducer>;\ntype ExistingSliceLike<DeclaredState, PreloadedState> = { [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>> }[keyof DeclaredState];\nexport type InjectConfig = {\n  /**\n   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.\n   */\n  overrideExisting?: boolean;\n};\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;\n  };\n}\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;\ntype InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;\nconst isSliceLike = (maybeSliceLike: AnySliceLike | ReducerMap): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string';\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) => slices.flatMap<[string, Reducer]>(sliceOrMap => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original');\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE];\nconst stateProxyMap = new WeakMap<object, object>();\nconst createStateProxy = <State extends object,>(state: State, reducerMap: Partial<Record<PropertyKey, Reducer>>, initialStateCache: Record<PropertyKey, unknown>) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {\n  get: (target, prop, receiver) => {\n    if (prop === ORIGINAL_STATE) return target;\n    const result = Reflect.get(target, prop, receiver);\n    if (typeof result === 'undefined') {\n      const cached = initialStateCache[prop];\n      if (typeof cached !== 'undefined') return cached;\n      const reducer = reducerMap[prop];\n      if (reducer) {\n        // ensure action type is random, to prevent reducer treating it differently\n        const reducerResult = reducer(undefined, {\n          type: nanoid()\n        });\n        if (typeof reducerResult === 'undefined') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). ` + `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + `you can use null instead of undefined.`);\n        }\n        initialStateCache[prop] = reducerResult;\n        return reducerResult;\n      }\n    }\n    return result;\n  }\n})) as State;\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(25) : 'original must be used on state Proxy');\n  }\n  return state[ORIGINAL_STATE];\n};\nconst emptyObject = {};\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state;\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>> {\n  const reducerMap = Object.fromEntries(getReducers(slices));\n  const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;\n  let reducer = getReducer();\n  function combinedReducer(state: Record<string, unknown>, action: UnknownAction) {\n    return reducer(state, action);\n  }\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n  const initialStateCache: Record<PropertyKey, unknown> = {};\n  const inject = (slice: AnySliceLike, config: InjectConfig = {}): typeof combinedReducer => {\n    const {\n      reducerPath,\n      reducer: reducerToInject\n    } = slice;\n    const currentReducer = reducerMap[reducerPath];\n    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n      }\n      return combinedReducer;\n    }\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath];\n    }\n    reducerMap[reducerPath] = reducerToInject;\n    reducer = getReducer();\n    return combinedReducer;\n  };\n  const selector = Object.assign(function makeSelector<State extends object, RootState, Args extends any[]>(selectorFn: (state: State, ...args: Args) => any, selectState?: (rootState: RootState, ...args: Args) => State) {\n    return function selector(state: State, ...args: Args) {\n      return selectorFn(createStateProxy(selectState ? selectState(state as any, ...args) : state, reducerMap, initialStateCache), ...args);\n    };\n  }, {\n    original\n  });\n  return Object.assign(combinedReducer, {\n    inject,\n    selector\n  }) as any;\n}","/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` + 'use the non-minified dev environment for full errors. ';\n}"],"mappings":"2eAAA,IAAAA,EAAA,GAAAC,GAAAD,EAAA,iBAAAE,GAAA,qBAAAC,GAAA,mBAAAC,EAAA,UAAAC,EAAA,gBAAAC,GAAA,sBAAAC,GAAA,sBAAAC,GAAA,qBAAAC,GAAA,sBAAAC,GAAA,kBAAAC,GAAA,mBAAAC,GAAA,iBAAAC,EAAA,2CAAAC,GAAA,qBAAAC,GAAA,4BAAAC,EAAA,mCAAAC,GAAA,4BAAAC,GAAA,wBAAAC,GAAA,4CAAAC,GAAA,6BAAAC,GAAA,gDAAAC,GAAA,sIAAAC,GAAA,gBAAAC,GAAA,mDAAAC,GAAA,2BAAAC,EAAA,yCAAAC,GAAA,YAAAC,EAAA,YAAAC,EAAA,uBAAAC,GAAA,+CAAAC,GAAA,gBAAAC,GAAA,uBAAAC,GAAA,cAAAC,GAAA,YAAAC,GAAA,eAAAC,EAAA,wBAAAC,GAAA,oDAAAC,GAAA,WAAAC,EAAA,gDAAAC,GAAA,mBAAAC,GAAA,iBAAAC,GAAA,qDAAAC,GAAA3C,GAGA4C,EAAA5C,EAAc,iBAHd,gBAIA,IAAA6C,GAAiC,iBCJjC,IAAAC,EAAiG,iBDOjG,IAAAC,GAA2C,oBEP3C,IAAAC,EAAsD,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AI,iFACtG","names":["src_exports","__export","ReducerType","SHOULD_AUTOBATCH","TaskAbortError","Tuple","addListener","asyncThunkCreator","autoBatchEnhancer","buildCreateSlice","clearAllListeners","combineSlices","configureStore","createAction","createActionCreatorInvariantMiddleware","createAsyncThunk","createDraftSafeSelector","createDraftSafeSelectorCreator","createDynamicMiddleware","createEntityAdapter","createImmutableStateInvariantMiddleware","createListenerMiddleware","createReducer","createSerializableStateInvariantMiddleware","createSlice","findNonSerializableValue","formatProdErrorMessage","isActionCreator","isAllOf","isAnyOf","isAsyncThunkAction","isFSA","isFulfilled","isImmutableDefault","isPending","isPlain","isRejected","isRejectedWithValue","miniSerializeError","nanoid","prepareAutoBatched","removeListener","unwrapResult","__toCommonJS","__reExport","import_immer","import_immer","import_reselect","import_reselect","createDraftSafeSelectorCreator","args","createSelector","createDraftSafeSelector","selector","wrappedSelector","value","rest","import_redux","composeWithDevTools","devToolsEnhancer","noop","import_redux_thunk","hasMatchFunction","v","createAction","type","prepareAction","actionCreator","args","prepared","formatProdErrorMessage","action","isActionCreator","hasMatchFunction","isFSA","isValidKey","key","getMessage","type","splitType","actionName","createActionCreatorInvariantMiddleware","options","next","action","Tuple","_Tuple","items","arr","freezeDraftable","val","getOrInsertComputed","map","key","compute","isImmutableDefault","value","createImmutableStateInvariantMiddleware","options","next","action","stringify","getSerialize","isPlain","val","type","findNonSerializableValue","value","path","isSerializable","getEntries","ignoredPaths","cache","foundNestedSerializable","entries","hasIgnoredPaths","key","nestedValue","nestedPath","ignored","isNestedFrozen","createSerializableStateInvariantMiddleware","options","next","action","isBoolean","x","buildGetDefaultMiddleware","options","thunk","immutableCheck","serializableCheck","actionCreatorCheck","middlewareArray","Tuple","thunkMiddleware","SHOULD_AUTOBATCH","prepareAutoBatched","payload","createQueueWithTimer","timeout","notify","autoBatchEnhancer","options","next","args","store","notifying","shouldNotifyAtEndOfTick","notificationQueued","listeners","queueCallback","notifyListeners","l","listener","wrappedListener","unsubscribe","action","buildGetDefaultEnhancers","middlewareEnhancer","options","autoBatch","enhancerArray","Tuple","autoBatchEnhancer","configureStore","options","getDefaultMiddleware","buildGetDefaultMiddleware","reducer","middleware","devTools","duplicateMiddlewareCheck","preloadedState","enhancers","rootReducer","formatProdErrorMessage","finalMiddleware","finalCompose","composeWithDevTools","middlewareEnhancer","getDefaultEnhancers","buildGetDefaultEnhancers","storeEnhancers","composedEnhancer","executeReducerBuilderCallback","builderCallback","actionsMap","actionMatchers","defaultCaseReducer","builder","typeOrActionCreator","reducer","type","formatProdErrorMessage","asyncThunk","reducers","matcher","isStateFunction","x","createReducer","initialState","mapOrBuilderCallback","actionsMap","finalActionMatchers","finalDefaultCaseReducer","executeReducerBuilderCallback","getInitialState","freezeDraftable","frozenInitialState","reducer","state","action","caseReducers","matcher","cr","previousState","caseReducer","result","draft","matches","matcher","action","hasMatchFunction","isAnyOf","matchers","isAllOf","hasExpectedRequestMetadata","validStatus","hasValidRequestId","hasValidRequestStatus","isAsyncThunkArray","a","isPending","asyncThunks","asyncThunk","isRejected","isRejectedWithValue","hasFlag","isFulfilled","isAsyncThunkAction","urlAlphabet","nanoid","size","id","i","commonProperties","RejectWithValue","payload","meta","FulfillWithMeta","miniSerializeError","value","simpleError","property","externalAbortMessage","createAsyncThunk","typePrefix","payloadCreator","options","fulfilled","createAction","requestId","arg","pending","rejected","error","actionCreator","signal","dispatch","getState","extra","nanoid","abortController","abortHandler","abortReason","abort","reason","promise","finalAction","conditionResult","isThenable","abortedPromise","_","reject","result","err","unwrapResult","isAnyOf","action","asyncThunkSymbol","asyncThunkCreator","createAsyncThunk","ReducerType","getType","slice","actionKey","buildCreateSlice","creators","cAT","options","name","reducerPath","formatProdErrorMessage","reducers","buildReducerCreators","reducerNames","context","contextMethods","typeOrActionCreator","reducer","type","matcher","actionCreator","reducerName","reducerDefinition","reducerDetails","isAsyncThunkSliceReducerDefinition","handleThunkCaseReducerDefinition","handleNormalReducerDefinition","buildReducer","extraReducers","actionMatchers","defaultCaseReducer","executeReducerBuilderCallback","finalCaseReducers","createReducer","builder","key","sM","m","selectSelf","state","injectedSelectorCache","injectedStateCache","_reducer","action","getInitialState","makeSelectorProps","injected","selectSlice","sliceState","getOrInsertComputed","getSelectors","selectState","selectorCache","map","selector","wrapSelector","injectable","pathOpt","config","newReducerPath","wrapper","rootState","args","createSlice","asyncThunk","payloadCreator","caseReducer","prepare","createNotation","maybeReducerWithPrepare","prepareCallback","isCaseReducerWithPrepareDefinition","createAction","fulfilled","pending","rejected","settled","thunk","noop","getInitialEntityState","createInitialStateFactory","stateAdapter","getInitialState","additionalState","entities","state","createSelectorsFactory","getSelectors","selectState","options","createSelector","createDraftSafeSelector","selectIds","state","selectEntities","selectAll","ids","entities","id","selectId","_","selectById","selectTotal","selectGlobalizedEntities","isDraftTyped","createSingleArgumentStateOperator","mutator","operator","createStateOperator","_","state","arg","isPayloadActionArgument","isFSA","runMutator","draft","selectIdValue","entity","selectId","ensureEntitiesArray","entities","getCurrent","value","splitAddedUpdatedEntities","newEntities","state","existingIdsArray","existingIds","added","addedIds","updated","id","createUnsortedStateAdapter","selectId","addOneMutably","entity","state","key","selectIdValue","addManyMutably","newEntities","ensureEntitiesArray","setOneMutably","setManyMutably","setAllMutably","removeOneMutably","removeManyMutably","keys","didMutate","id","removeAllMutably","takeNewKey","update","original","updated","newKey","hasNewKey","updateOneMutably","updateManyMutably","updates","newKeys","updatesPerEntity","e","upsertOneMutably","upsertManyMutably","added","splitAddedUpdatedEntities","createSingleArgumentStateOperator","createStateOperator","findInsertIndex","sortedItems","item","comparisonFunction","lowIndex","highIndex","middleIndex","currentItem","insert","insertAtIndex","createSortedStateAdapter","selectId","comparer","removeOne","removeMany","removeAll","createUnsortedStateAdapter","addOneMutably","entity","state","addManyMutably","newEntities","existingIds","ensureEntitiesArray","existingKeys","getCurrent","addedKeys","models","model","modelId","selectIdValue","notAdded","mergeFunction","setOneMutably","setManyMutably","deduplicatedEntities","entityId","setAllMutably","updateOneMutably","update","updateManyMutably","updates","appliedUpdates","replacedIds","newId","oldIndex","upsertOneMutably","upsertManyMutably","added","updated","existingIdsArray","splitAddedUpdatedEntities","areArraysEqual","a","b","i","addedItems","currentEntities","currentIds","stateEntities","ids","sortedEntities","id","wasPreviouslyEmpty","newSortedIds","createStateOperator","createEntityAdapter","options","selectId","sortComparer","instance","stateAdapter","createSortedStateAdapter","createUnsortedStateAdapter","stateFactory","createInitialStateFactory","selectorsFactory","createSelectorsFactory","task","listener","completed","cancelled","taskCancelled","taskCompleted","listenerCancelled","listenerCompleted","TaskAbortError","code","assertFunction","func","expected","formatProdErrorMessage","noop","catchRejection","promise","onError","addAbortSignalListener","abortSignal","callback","validateActive","signal","TaskAbortError","raceWithSignal","promise","cleanup","noop","resolve","reject","notifyRejection","addAbortSignalListener","runTask","task","cleanUp","error","createPause","catchRejection","output","createDelay","pause","timeoutMs","assign","INTERNAL_NIL_TOKEN","alm","createFork","parentAbortSignal","parentBlockingPromises","linkControllers","controller","addAbortSignalListener","taskExecutor","opts","assertFunction","childAbortController","result","runTask","validateActive","createPause","createDelay","taskCompleted","noop","taskCancelled","createTakePattern","startListening","signal","take","predicate","timeout","unsubscribe","promises","resolve","reject","stopListening","action","listenerApi","output","raceWithSignal","catchRejection","getListenerEntryPropsFrom","options","type","actionCreator","matcher","effect","createAction","formatProdErrorMessage","createListenerEntry","nanoid","findListenerEntry","listenerMap","entry","cancelActiveListeners","listenerCancelled","createClearListenerMiddleware","executingListeners","listener","safelyNotifyError","errorHandler","errorToNotify","errorInfo","errorHandlerError","addListener","clearAllListeners","removeListener","defaultErrorHandler","args","createListenerMiddleware","middlewareOptions","trackExecutingListener","count","untrackExecutingListener","extra","onError","insertEntry","cancelOptions","notifyListener","api","getOriginalState","internalTaskController","autoJoinPromises","_","set","listenerError","TaskAbortError","listenerCompleted","clearListenerMiddleware","next","originalState","currentState","listenerEntries","runListener","predicateError","createMiddlewareEntry","middleware","matchInstance","instanceId","action","createDynamicMiddleware","nanoid","middlewareMap","withMiddleware","createAction","middlewares","addMiddleware","getOrInsertComputed","getFinalMiddleware","api","appliedMiddleware","entry","isWithMiddleware","isAllOf","next","import_redux","isSliceLike","maybeSliceLike","getReducers","slices","sliceOrMap","ORIGINAL_STATE","isStateProxy","value","stateProxyMap","createStateProxy","state","reducerMap","initialStateCache","getOrInsertComputed","target","prop","receiver","result","cached","reducer","reducerResult","nanoid","formatProdErrorMessage","original","emptyObject","noopReducer","combineSlices","getReducer","combinedReducer","action","inject","slice","config","reducerPath","reducerToInject","currentReducer","selector","selectorFn","selectState","args","formatProdErrorMessage","code"]}
Index: node_modules/@reduxjs/toolkit/dist/index.d.mts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2662 @@
+import { ActionCreator, Action, Middleware, StoreEnhancer, UnknownAction, Reducer, ReducersMapObject, Store, Dispatch, StateFromReducersMapObject, PreloadedStateShapeFromReducersMapObject, MiddlewareAPI } from 'redux';
+export * from 'redux';
+import { Draft } from 'immer';
+export { Draft, WritableDraft, produce as createNextState, current, freeze, isDraft, original } from 'immer';
+import * as reselect from 'reselect';
+import { weakMapMemoize, createSelectorCreator, Selector, CreateSelectorFunction } from 'reselect';
+export { OutputSelector, Selector, createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from 'reselect';
+import { ThunkMiddleware, ThunkDispatch } from 'redux-thunk';
+export { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';
+import { UncheckedIndexedAccess } from './uncheckedindexed.js';
+
+declare const createDraftSafeSelectorCreator: typeof createSelectorCreator;
+/**
+ * "Draft-Safe" version of `reselect`'s `createSelector`:
+ * If an `immer`-drafted object is passed into the resulting selector's first argument,
+ * the selector will act on the current draft value, instead of returning a cached value
+ * that might be possibly outdated if the draft has been modified since.
+ * @public
+ */
+declare const createDraftSafeSelector: reselect.CreateSelectorFunction<typeof weakMapMemoize, typeof weakMapMemoize, any>;
+
+/**
+ * @public
+ */
+interface DevToolsEnhancerOptions {
+    /**
+     * the instance name to be showed on the monitor page. Default value is `document.title`.
+     * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
+     */
+    name?: string;
+    /**
+     * action creators functions to be available in the Dispatcher.
+     */
+    actionCreators?: ActionCreator<any>[] | {
+        [key: string]: ActionCreator<any>;
+    };
+    /**
+     * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
+     * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
+     * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
+     *
+     * @default 500 ms.
+     */
+    latency?: number;
+    /**
+     * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
+     *
+     * @default 50
+     */
+    maxAge?: number;
+    /**
+     * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
+     * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
+     * functions.
+     */
+    serialize?: boolean | {
+        /**
+         * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
+         * - `false` - will handle also circular references.
+         * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
+         * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
+         *   For each of them you can indicate if to include (by setting as `true`).
+         *   For `function` key you can also specify a custom function which handles serialization.
+         *   See [`jsan`](https://github.com/kolodny/jsan) for more details.
+         */
+        options?: undefined | boolean | {
+            date?: true;
+            regex?: true;
+            undefined?: true;
+            error?: true;
+            symbol?: true;
+            map?: true;
+            set?: true;
+            function?: true | ((fn: (...args: any[]) => any) => string);
+        };
+        /**
+         * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
+         * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
+         * key. So you can deserialize it back while importing or persisting data.
+         * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
+         */
+        replacer?: (key: string, value: unknown) => any;
+        /**
+         * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
+         * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
+         * as an example on how to serialize special data types and get them back.
+         */
+        reviver?: (key: string, value: unknown) => any;
+        /**
+         * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
+         * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
+         * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
+         */
+        immutable?: any;
+        /**
+         * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
+         */
+        refs?: any;
+    };
+    /**
+     * function which takes `action` object and id number as arguments, and should return `action` object back.
+     */
+    actionSanitizer?: <A extends Action>(action: A, id: number) => A;
+    /**
+     * function which takes `state` object and index as arguments, and should return `state` object back.
+     */
+    stateSanitizer?: <S>(state: S, index: number) => S;
+    /**
+     * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+     * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+     */
+    actionsDenylist?: string | string[];
+    /**
+     * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+     * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+     */
+    actionsAllowlist?: string | string[];
+    /**
+     * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
+     * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
+     */
+    predicate?: <S, A extends Action>(state: S, action: A) => boolean;
+    /**
+     * if specified as `false`, it will not record the changes till clicking on `Start recording` button.
+     * Available only for Redux enhancer, for others use `autoPause`.
+     *
+     * @default true
+     */
+    shouldRecordChanges?: boolean;
+    /**
+     * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
+     * If not specified, will commit when paused. Available only for Redux enhancer.
+     *
+     * @default "@@PAUSED""
+     */
+    pauseActionType?: string;
+    /**
+     * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
+     * Not available for Redux enhancer (as it already does it but storing the data to be sent).
+     *
+     * @default false
+     */
+    autoPause?: boolean;
+    /**
+     * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
+     * Available only for Redux enhancer.
+     *
+     * @default false
+     */
+    shouldStartLocked?: boolean;
+    /**
+     * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
+     *
+     * @default true
+     */
+    shouldHotReload?: boolean;
+    /**
+     * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
+     *
+     * @default false
+     */
+    shouldCatchErrors?: boolean;
+    /**
+     * If you want to restrict the extension, specify the features you allow.
+     * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
+     * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
+     * Otherwise, you'll get/set the data right from the monitor part.
+     */
+    features?: {
+        /**
+         * start/pause recording of dispatched actions
+         */
+        pause?: boolean;
+        /**
+         * lock/unlock dispatching actions and side effects
+         */
+        lock?: boolean;
+        /**
+         * persist states on page reloading
+         */
+        persist?: boolean;
+        /**
+         * export history of actions in a file
+         */
+        export?: boolean | 'custom';
+        /**
+         * import history of actions from a file
+         */
+        import?: boolean | 'custom';
+        /**
+         * jump back and forth (time travelling)
+         */
+        jump?: boolean;
+        /**
+         * skip (cancel) actions
+         */
+        skip?: boolean;
+        /**
+         * drag and drop actions in the history list
+         */
+        reorder?: boolean;
+        /**
+         * dispatch custom actions or action creators
+         */
+        dispatch?: boolean;
+        /**
+         * generate tests for the selected actions
+         */
+        test?: boolean;
+    };
+    /**
+     * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
+     * Defaults to false.
+     */
+    trace?: boolean | (<A extends Action>(action: A) => string);
+    /**
+     * The maximum number of stack trace entries to record per action. Defaults to 10.
+     */
+    traceLimit?: number;
+}
+
+interface ActionCreatorInvariantMiddlewareOptions {
+    /**
+     * The function to identify whether a value is an action creator.
+     * The default checks for a function with a static type property and match method.
+     */
+    isActionCreator?: (action: unknown) => action is Function & {
+        type?: unknown;
+    };
+}
+declare function createActionCreatorInvariantMiddleware(options?: ActionCreatorInvariantMiddlewareOptions): Middleware;
+
+/**
+ * Returns true if the passed value is "plain", i.e. a value that is either
+ * directly JSON-serializable (boolean, number, string, array, plain object)
+ * or `undefined`.
+ *
+ * @param val The value to check.
+ *
+ * @public
+ */
+declare function isPlain(val: any): boolean;
+interface NonSerializableValue {
+    keyPath: string;
+    value: unknown;
+}
+type IgnorePaths = readonly (string | RegExp)[];
+/**
+ * @public
+ */
+declare function findNonSerializableValue(value: unknown, path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], ignoredPaths?: IgnorePaths, cache?: WeakSet<object>): NonSerializableValue | false;
+/**
+ * Options for `createSerializableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+interface SerializableStateInvariantMiddlewareOptions {
+    /**
+     * The function to check if a value is considered serializable. This
+     * function is applied recursively to every value contained in the
+     * state. Defaults to `isPlain()`.
+     */
+    isSerializable?: (value: any) => boolean;
+    /**
+     * The function that will be used to retrieve entries from each
+     * value.  If unspecified, `Object.entries` will be used. Defaults
+     * to `undefined`.
+     */
+    getEntries?: (value: any) => [string, any][];
+    /**
+     * An array of action types to ignore when checking for serializability.
+     * Defaults to []
+     */
+    ignoredActions?: string[];
+    /**
+     * An array of dot-separated path strings or regular expressions to ignore
+     * when checking for serializability, Defaults to
+     * ['meta.arg', 'meta.baseQueryMeta']
+     */
+    ignoredActionPaths?: (string | RegExp)[];
+    /**
+     * An array of dot-separated path strings or regular expressions to ignore
+     * when checking for serializability, Defaults to []
+     */
+    ignoredPaths?: (string | RegExp)[];
+    /**
+     * Execution time warning threshold. If the middleware takes longer
+     * than `warnAfter` ms, a warning will be displayed in the console.
+     * Defaults to 32ms.
+     */
+    warnAfter?: number;
+    /**
+     * Opt out of checking state. When set to `true`, other state-related params will be ignored.
+     */
+    ignoreState?: boolean;
+    /**
+     * Opt out of checking actions. When set to `true`, other action-related params will be ignored.
+     */
+    ignoreActions?: boolean;
+    /**
+     * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.
+     * The cache is automatically disabled if no browser support for WeakSet is present.
+     */
+    disableCache?: boolean;
+}
+/**
+ * Creates a middleware that, after every state change, checks if the new
+ * state is serializable. If a non-serializable value is found within the
+ * state, an error is printed to the console.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+declare function createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware;
+
+/**
+ * The default `isImmutable` function.
+ *
+ * @public
+ */
+declare function isImmutableDefault(value: unknown): boolean;
+type IsImmutableFunc = (value: any) => boolean;
+/**
+ * Options for `createImmutableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+interface ImmutableStateInvariantMiddlewareOptions {
+    /**
+      Callback function to check if a value is considered to be immutable.
+      This function is applied recursively to every value contained in the state.
+      The default implementation will return true for primitive types
+      (like numbers, strings, booleans, null and undefined).
+     */
+    isImmutable?: IsImmutableFunc;
+    /**
+      An array of dot-separated path strings that match named nodes from
+      the root state to ignore when checking for immutability.
+      Defaults to undefined
+     */
+    ignoredPaths?: IgnorePaths;
+    /** Print a warning if checks take longer than N ms. Default: 32ms */
+    warnAfter?: number;
+}
+/**
+ * Creates a middleware that checks whether any state was mutated in between
+ * dispatches or during a dispatch. If any mutations are detected, an error is
+ * thrown.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+declare function createImmutableStateInvariantMiddleware(options?: ImmutableStateInvariantMiddlewareOptions): Middleware;
+
+declare class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {
+    constructor(length: number);
+    constructor(...items: Items);
+    static get [Symbol.species](): any;
+    concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;
+    concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
+    concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
+    prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;
+    prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
+    prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
+}
+
+/**
+ * return True if T is `any`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
+type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
+/**
+ * return True if T is `unknown`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;
+type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;
+/**
+ * @internal
+ */
+type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;
+/**
+ * @internal
+ */
+type IfVoid<P, True, False> = [void] extends [P] ? True : False;
+/**
+ * @internal
+ */
+type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;
+/**
+ * returns True if TS version is above 3.5, False if below.
+ * uses feature detection to detect TS version >= 3.5
+ * * versions below 3.5 will return `{}` for unresolvable interference
+ * * versions above will return `unknown`
+ *
+ * @internal
+ */
+type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<(<T>() => T)>, 0, 1>];
+/**
+ * @internal
+ */
+type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
+type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
+    infer Head,
+    ...infer Tail
+] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;
+type ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;
+type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;
+type ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;
+type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;
+type ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;
+type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;
+/**
+ * Helper type. Passes T out again, but boxes it in a way that it cannot
+ * "widen" the type by accident if it is a generic that should be inferred
+ * from elsewhere.
+ *
+ * @internal
+ */
+type NoInfer<T> = [T][T extends any ? 0 : never];
+type NonUndefined<T> = T extends undefined ? never : T;
+type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
+type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
+interface TypeGuard<T> {
+    (value: any): value is T;
+}
+interface HasMatchFunction<T> {
+    match: TypeGuard<T>;
+}
+/** @public */
+type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;
+/** @public */
+type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;
+type Id<T> = {
+    [K in keyof T]: T[K];
+} & {};
+type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;
+type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;
+/**
+ * A Promise that will never reject.
+ * @see https://github.com/reduxjs/redux-toolkit/issues/4101
+ */
+type SafePromise<T> = Promise<T> & {
+    __linterBrands: 'SafePromise';
+};
+
+interface ThunkOptions<E = any> {
+    extraArgument: E;
+}
+interface GetDefaultMiddlewareOptions {
+    thunk?: boolean | ThunkOptions;
+    immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;
+    serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;
+    actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;
+}
+type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {
+    thunk: false;
+} ? never : O extends {
+    thunk: {
+        extraArgument: infer E;
+    };
+} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;
+type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {
+    thunk: true;
+    immutableCheck: true;
+    serializableCheck: true;
+    actionCreatorCheck: true;
+}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
+
+declare const SHOULD_AUTOBATCH = "RTK_autoBatch";
+declare const prepareAutoBatched: <T>() => (payload: T) => {
+    payload: T;
+    meta: unknown;
+};
+type AutoBatchOptions = {
+    type: 'tick';
+} | {
+    type: 'timer';
+    timeout: number;
+} | {
+    type: 'raf';
+} | {
+    type: 'callback';
+    queueNotification: (notify: () => void) => void;
+};
+/**
+ * A Redux store enhancer that watches for "low-priority" actions, and delays
+ * notifying subscribers until either the queued callback executes or the
+ * next "standard-priority" action is dispatched.
+ *
+ * This allows dispatching multiple "low-priority" actions in a row with only
+ * a single subscriber notification to the UI after the sequence of actions
+ * is finished, thus improving UI re-render performance.
+ *
+ * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
+ * This can be added to `action.meta` manually, or by using the
+ * `prepareAutoBatched` helper.
+ *
+ * By default, it will queue a notification for the end of the event loop tick.
+ * However, you can pass several other options to configure the behavior:
+ * - `{type: 'tick'}`: queues using `queueMicrotask`
+ * - `{type: 'timer', timeout: number}`: queues using `setTimeout`
+ * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
+ * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
+ *
+ *
+ */
+declare const autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;
+
+type GetDefaultEnhancersOptions = {
+    autoBatch?: boolean | AutoBatchOptions;
+};
+type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{
+    dispatch: ExtractDispatchExtensions<M>;
+}>]>;
+
+/**
+ * Options for `configureStore()`.
+ *
+ * @public
+ */
+interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {
+    /**
+     * A single reducer function that will be used as the root reducer, or an
+     * object of slice reducers that will be passed to `combineReducers()`.
+     */
+    reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;
+    /**
+     * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
+     * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
+     *
+     * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
+     * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
+     */
+    middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;
+    /**
+     * Whether to enable Redux DevTools integration. Defaults to `true`.
+     *
+     * Additional configuration can be done by passing Redux DevTools options
+     */
+    devTools?: boolean | DevToolsEnhancerOptions;
+    /**
+     * Whether to check for duplicate middleware instances. Defaults to `true`.
+     */
+    duplicateMiddlewareCheck?: boolean;
+    /**
+     * The initial state, same as Redux's createStore.
+     * You may optionally specify it to hydrate the state
+     * from the server in universal apps, or to restore a previously serialized
+     * user session. If you use `combineReducers()` to produce the root reducer
+     * function (either directly or indirectly by passing an object as `reducer`),
+     * this must be an object with the same shape as the reducer map keys.
+     */
+    preloadedState?: P;
+    /**
+     * The store enhancers to apply. See Redux's `createStore()`.
+     * All enhancers will be included before the DevTools Extension enhancer.
+     * If you need to customize the order of enhancers, supply a callback
+     * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
+     * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
+     * If you only need to add middleware, you can use the `middleware` parameter instead.
+     */
+    enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;
+}
+type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;
+type Enhancers = ReadonlyArray<StoreEnhancer>;
+/**
+ * A Redux store returned by `configureStore()`. Supports dispatching
+ * side-effectful _thunks_ in addition to plain actions.
+ *
+ * @public
+ */
+type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;
+/**
+ * A friendly abstraction over the standard Redux `createStore()` function.
+ *
+ * @param options The store configuration.
+ * @returns A configured Redux store.
+ *
+ * @public
+ */
+declare function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[
+    StoreEnhancer<{
+        dispatch: ExtractDispatchExtensions<M>;
+    }>,
+    StoreEnhancer
+]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E>;
+
+/**
+ * An action with a string type and an associated payload. This is the
+ * type of action returned by `createAction()` action creators.
+ *
+ * @template P The type of the action's payload.
+ * @template T the type used for the action type.
+ * @template M The type of the action's meta (optional)
+ * @template E The type of the action's error (optional)
+ *
+ * @public
+ */
+type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
+    payload: P;
+    type: T;
+} & ([M] extends [never] ? {} : {
+    meta: M;
+}) & ([E] extends [never] ? {} : {
+    error: E;
+});
+/**
+ * A "prepare" method to be used as the second parameter of `createAction`.
+ * Takes any number of arguments and returns a Flux Standard Action without
+ * type (will be added later) that *must* contain a payload (might be undefined).
+ *
+ * @public
+ */
+type PrepareAction<P> = ((...args: any[]) => {
+    payload: P;
+}) | ((...args: any[]) => {
+    payload: P;
+    meta: any;
+}) | ((...args: any[]) => {
+    payload: P;
+    error: any;
+}) | ((...args: any[]) => {
+    payload: P;
+    meta: any;
+    error: any;
+});
+/**
+ * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
+ *
+ * @internal
+ */
+type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {
+    error: infer E;
+} ? E : never, ReturnType<PA> extends {
+    meta: infer M;
+} ? M : never> : void;
+/**
+ * Basic type for all action creators.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ */
+type BaseActionCreator<P, T extends string, M = never, E = never> = {
+    type: T;
+    match: (action: unknown) => action is PayloadAction<P, T, M, E>;
+};
+/**
+ * An action creator that takes multiple arguments that are passed
+ * to a `PrepareAction` method to create the final Action.
+ * @typeParam Args arguments for the action creator function
+ * @typeParam P `payload` type
+ * @typeParam T `type` name
+ * @typeParam E optional `error` type
+ * @typeParam M optional `meta` type
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
+    /**
+     * Calling this {@link redux#ActionCreator} with `Args` will return
+     * an Action with a payload of type `P` and (depending on the `PrepareAction`
+     * method used) a `meta`- and `error` property of types `M` and `E` respectively.
+     */
+    (...args: Args): PayloadAction<P, T, M, E>;
+}
+/**
+ * An action creator of type `T` that takes an optional payload of type `P`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} with an argument will
+     * return a {@link PayloadAction} of type `T` with a payload of `P`.
+     * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
+     */
+    (payload?: P): PayloadAction<P, T>;
+}
+/**
+ * An action creator of type `T` that takes no payload.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} will
+     * return a {@link PayloadAction} of type `T` with a payload of `undefined`
+     */
+    (noArgument: void): PayloadAction<undefined, T>;
+}
+/**
+ * An action creator of type `T` that requires a payload of type P.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} with an argument will
+     * return a {@link PayloadAction} of type `T` with a payload of `P`
+     */
+    (payload: P): PayloadAction<P, T>;
+}
+/**
+ * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} with an argument will
+     * return a {@link PayloadAction} of type `T` with a payload
+     * of exactly the type of the argument.
+     */
+    <PT extends unknown>(payload: PT): PayloadAction<PT, T>;
+}
+/**
+ * An action creator that produces actions with a `payload` attribute.
+ *
+ * @typeParam P the `payload` type
+ * @typeParam T the `type` of the resulting action
+ * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
+ *
+ * @public
+ */
+type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>, IfVoid<P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T>>>>>>;
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;
+/**
+ * Returns true if value is an RTK-like action creator, with a static type property and match method.
+ */
+declare function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function;
+/**
+ * Returns true if value is an action with a string type and valid Flux Standard Action keys.
+ */
+declare function isFSA(action: unknown): action is {
+    type: string;
+    payload?: unknown;
+    error?: unknown;
+    meta?: unknown;
+};
+type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
+
+type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {
+    dispatch: D;
+    getState: () => S;
+    extra: E;
+    requestId: string;
+    signal: AbortSignal;
+    abort: (reason?: string) => void;
+    rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;
+    fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;
+};
+/**
+ * @public
+ */
+interface SerializedError {
+    name?: string;
+    message?: string;
+    stack?: string;
+    code?: string;
+}
+declare class RejectWithValue<Payload, RejectedMeta> {
+    readonly payload: Payload;
+    readonly meta: RejectedMeta;
+    private readonly _type;
+    constructor(payload: Payload, meta: RejectedMeta);
+}
+declare class FulfillWithMeta<Payload, FulfilledMeta> {
+    readonly payload: Payload;
+    readonly meta: FulfilledMeta;
+    private readonly _type;
+    constructor(payload: Payload, meta: FulfilledMeta);
+}
+/**
+ * Serializes an error into a plain object.
+ * Reworked from https://github.com/sindresorhus/serialize-error
+ *
+ * @public
+ */
+declare const miniSerializeError: (value: any) => SerializedError;
+type AsyncThunkConfig = {
+    state?: unknown;
+    dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;
+    extra?: unknown;
+    rejectValue?: unknown;
+    serializedErrorType?: unknown;
+    pendingMeta?: unknown;
+    fulfilledMeta?: unknown;
+    rejectedMeta?: unknown;
+};
+type GetState<ThunkApiConfig> = ThunkApiConfig extends {
+    state: infer State;
+} ? State : unknown;
+type GetExtra<ThunkApiConfig> = ThunkApiConfig extends {
+    extra: infer Extra;
+} ? Extra : unknown;
+type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
+    dispatch: infer Dispatch;
+} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;
+type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;
+type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
+    rejectValue: infer RejectValue;
+} ? RejectValue : unknown;
+type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
+    pendingMeta: infer PendingMeta;
+} ? PendingMeta : unknown;
+type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
+    fulfilledMeta: infer FulfilledMeta;
+} ? FulfilledMeta : unknown;
+type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
+    rejectedMeta: infer RejectedMeta;
+} ? RejectedMeta : unknown;
+type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
+    serializedErrorType: infer GetSerializedErrorType;
+} ? GetSerializedErrorType : SerializedError;
+type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);
+/**
+ * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;
+/**
+ * A type describing the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
+/**
+ * A ThunkAction created by `createAsyncThunk`.
+ * Dispatching it returns a Promise for either a
+ * fulfilled or rejected action.
+ * Also, the returned value contains an `abort()` method
+ * that allows the asyncAction to be cancelled from the outside.
+ *
+ * @public
+ */
+type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {
+    abort: (reason?: string) => void;
+    requestId: string;
+    arg: ThunkArg;
+    unwrap: () => Promise<Returned>;
+};
+/**
+ * Config provided when calling the async thunk action creator.
+ */
+interface AsyncThunkDispatchConfig {
+    /**
+     * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
+     */
+    signal?: AbortSignal;
+}
+type AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, unknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [void] extends [ThunkArg] ? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [undefined] extends [ThunkArg] ? WithStrictNullChecks<(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> : (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;
+/**
+ * Options object for `createAsyncThunk`.
+ *
+ * @public
+ */
+type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {
+    /**
+     * A method to control whether the asyncThunk should be executed. Has access to the
+     * `arg`, `api.getState()` and `api.extra` arguments.
+     *
+     * @returns `false` if it should be skipped
+     */
+    condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;
+    /**
+     * If `condition` returns `false`, the asyncThunk will be skipped.
+     * This option allows you to control whether a `rejected` action with `meta.condition == false`
+     * will be dispatched or not.
+     *
+     * @default `false`
+     */
+    dispatchConditionRejection?: boolean;
+    serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;
+    /**
+     * A function to use when generating the `requestId` for the request sequence.
+     *
+     * @default `nanoid`
+     */
+    idGenerator?: (arg: ThunkArg) => string;
+} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     *
+     * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
+     * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
+     */
+    getPendingMeta?(base: {
+        arg: ThunkArg;
+        requestId: string;
+    }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
+}, {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     */
+    getPendingMeta(base: {
+        arg: ThunkArg;
+        requestId: string;
+    }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
+}>;
+type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
+    string,
+    ThunkArg,
+    GetPendingMeta<ThunkApiConfig>?
+], undefined, string, never, {
+    arg: ThunkArg;
+    requestId: string;
+    requestStatus: 'pending';
+} & GetPendingMeta<ThunkApiConfig>>;
+type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
+    Error | null,
+    string,
+    ThunkArg,
+    GetRejectValue<ThunkApiConfig>?,
+    GetRejectedMeta<ThunkApiConfig>?
+], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {
+    arg: ThunkArg;
+    requestId: string;
+    requestStatus: 'rejected';
+    aborted: boolean;
+    condition: boolean;
+} & (({
+    rejectedWithValue: false;
+} & {
+    [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined;
+}) | ({
+    rejectedWithValue: true;
+} & GetRejectedMeta<ThunkApiConfig>))>;
+type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
+    Returned,
+    string,
+    ThunkArg,
+    GetFulfilledMeta<ThunkApiConfig>?
+], Returned, string, never, {
+    arg: ThunkArg;
+    requestId: string;
+    requestStatus: 'fulfilled';
+} & GetFulfilledMeta<ThunkApiConfig>>;
+/**
+ * A type describing the return value of `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
+    pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;
+    rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;
+    fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;
+    settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;
+    typePrefix: string;
+};
+type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;
+type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {
+    /**
+     *
+     * @param typePrefix
+     * @param payloadCreator
+     * @param options
+     *
+     * @public
+     */
+    <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;
+    /**
+     *
+     * @param typePrefix
+     * @param payloadCreator
+     * @param options
+     *
+     * @public
+     */
+    <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
+};
+type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
+    withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
+};
+declare const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
+interface UnwrappableAction {
+    payload: any;
+    meta?: any;
+    error?: any;
+}
+type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {
+    error: any;
+}>['payload'];
+/**
+ * @public
+ */
+declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;
+type WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;
+
+type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {
+    pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;
+    rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;
+    fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;
+    settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;
+};
+type TypedActionCreator<Type extends string> = {
+    (...args: any[]): Action<Type>;
+    type: Type;
+};
+/**
+ * A builder for an action <-> reducer map.
+ *
+ * @public
+ */
+interface ActionReducerMapBuilder<State> {
+    /**
+     * Adds a case reducer to handle a single exact action type.
+     * @remarks
+     * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+     * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+     * @param reducer - The actual case reducer function.
+     */
+    addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;
+    /**
+     * Adds a case reducer to handle a single exact action type.
+     * @remarks
+     * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
+     * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+     * @param reducer - The actual case reducer function.
+     */
+    addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;
+    /**
+     * Adds case reducers to handle actions based on a `AsyncThunk` action creator.
+     * @remarks
+     * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+     * @param asyncThunk - The async thunk action creator itself.
+     * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
+     * @example
+  ```ts no-transpile
+  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'
+  
+  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
+    const response = await fetch(`https://reqres.in/api/users/${id}`)
+    return (await response.json()).data
+  })
+  
+  const reducer = createReducer(initialState, (builder) => {
+    builder.addAsyncThunk(fetchUserById, {
+      pending: (state, action) => {
+        state.fetchUserById.loading = 'pending'
+      },
+      fulfilled: (state, action) => {
+        state.fetchUserById.data = action.payload
+      },
+      rejected: (state, action) => {
+        state.fetchUserById.error = action.error
+      },
+      settled: (state, action) => {
+        state.fetchUserById.loading = action.meta.requestStatus
+      },
+    })
+  })
+     */
+    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;
+    /**
+     * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
+     * @remarks
+     * If multiple matcher reducers match, all of them will be executed in the order
+     * they were defined in - even if a case reducer already matched.
+     * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
+     * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
+     *   function
+     * @param reducer - The actual case reducer function.
+     *
+     * @example
+  ```ts
+  import {
+    createAction,
+    createReducer,
+    AsyncThunk,
+    UnknownAction,
+  } from "@reduxjs/toolkit";
+  
+  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
+  
+  type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
+  type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
+  type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
+  
+  const initialState: Record<string, string> = {};
+  const resetAction = createAction("reset-tracked-loading-state");
+  
+  function isPendingAction(action: UnknownAction): action is PendingAction {
+    return typeof action.type === "string" && action.type.endsWith("/pending");
+  }
+  
+  const reducer = createReducer(initialState, (builder) => {
+    builder
+      .addCase(resetAction, () => initialState)
+      // matcher can be defined outside as a type predicate function
+      .addMatcher(isPendingAction, (state, action) => {
+        state[action.meta.requestId] = "pending";
+      })
+      .addMatcher(
+        // matcher can be defined inline as a type predicate function
+        (action): action is RejectedAction => action.type.endsWith("/rejected"),
+        (state, action) => {
+          state[action.meta.requestId] = "rejected";
+        }
+      )
+      // matcher can just return boolean and the matcher can receive a generic argument
+      .addMatcher<FulfilledAction>(
+        (action) => action.type.endsWith("/fulfilled"),
+        (state, action) => {
+          state[action.meta.requestId] = "fulfilled";
+        }
+      );
+  });
+  ```
+     */
+    addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;
+    /**
+     * Adds a "default case" reducer that is executed if no case reducer and no matcher
+     * reducer was executed for this action.
+     * @param reducer - The fallback "default case" reducer function.
+     *
+     * @example
+  ```ts
+  import { createReducer } from '@reduxjs/toolkit'
+  const initialState = { otherActions: 0 }
+  const reducer = createReducer(initialState, builder => {
+    builder
+      // .addCase(...)
+      // .addMatcher(...)
+      .addDefaultCase((state, action) => {
+        state.otherActions++
+      })
+  })
+  ```
+     */
+    addDefaultCase(reducer: CaseReducer<State, Action>): {};
+}
+
+/**
+ * Defines a mapping from action types to corresponding action object shapes.
+ *
+ * @deprecated This should not be used manually - it is only used for internal
+ *             inference purposes and should not have any further value.
+ *             It might be removed in the future.
+ * @public
+ */
+type Actions<T extends keyof any = string> = Record<T, Action>;
+/**
+ * A *case reducer* is a reducer function for a specific action type. Case
+ * reducers can be composed to full reducers using `createReducer()`.
+ *
+ * Unlike a normal Redux reducer, a case reducer is never called with an
+ * `undefined` state to determine the initial state. Instead, the initial
+ * state is explicitly specified as an argument to `createReducer()`.
+ *
+ * In addition, a case reducer can choose to mutate the passed-in `state`
+ * value directly instead of returning a new state. This does not actually
+ * cause the store state to be mutated directly; instead, thanks to
+ * [immer](https://github.com/mweststrate/immer), the mutations are
+ * translated to copy operations that result in a new state.
+ *
+ * @public
+ */
+type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
+/**
+ * A mapping from action types to case reducers for `createReducer()`.
+ *
+ * @deprecated This should not be used manually - it is only used
+ *             for internal inference purposes and using it manually
+ *             would lead to type erasure.
+ *             It might be removed in the future.
+ * @public
+ */
+type CaseReducers<S, AS extends Actions> = {
+    [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;
+};
+type NotFunction<T> = T extends Function ? never : T;
+type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
+    getInitialState: () => S;
+};
+/**
+ * A utility function that allows defining a reducer as a mapping from action
+ * type to *case reducer* functions that handle these action types. The
+ * reducer's initial state is passed as the first argument.
+ *
+ * @remarks
+ * The body of every case reducer is implicitly wrapped with a call to
+ * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
+ * This means that rather than returning a new state object, you can also
+ * mutate the passed-in state object directly; these mutations will then be
+ * automatically and efficiently translated into copies, giving you both
+ * convenience and immutability.
+ *
+ * @overloadSummary
+ * This function accepts a callback that receives a `builder` object as its argument.
+ * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
+ * called to define what actions this reducer will handle.
+ *
+ * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+ * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
+ *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+ * @example
+```ts
+import {
+  createAction,
+  createReducer,
+  UnknownAction,
+  PayloadAction,
+} from "@reduxjs/toolkit";
+
+const increment = createAction<number>("increment");
+const decrement = createAction<number>("decrement");
+
+function isActionWithNumberPayload(
+  action: UnknownAction
+): action is PayloadAction<number> {
+  return typeof action.payload === "number";
+}
+
+const reducer = createReducer(
+  {
+    counter: 0,
+    sumOfNumberPayloads: 0,
+    unhandledActions: 0,
+  },
+  (builder) => {
+    builder
+      .addCase(increment, (state, action) => {
+        // action is inferred correctly here
+        state.counter += action.payload;
+      })
+      // You can chain calls, or have separate `builder.addCase()` lines each time
+      .addCase(decrement, (state, action) => {
+        state.counter -= action.payload;
+      })
+      // You can apply a "matcher function" to incoming actions
+      .addMatcher(isActionWithNumberPayload, (state, action) => {})
+      // and provide a default case if no other handlers matched
+      .addDefaultCase((state, action) => {});
+  }
+);
+```
+ * @public
+ */
+declare function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>;
+
+type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
+    reducerPath: ReducerPath;
+    reducer: Reducer<State, any, PreloadedState>;
+};
+type AnySliceLike = SliceLike<string, any>;
+type SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;
+type SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;
+type SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;
+type WithSlice<A extends AnySliceLike> = {
+    [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>;
+};
+type WithSlicePreloadedState<A extends AnySliceLike> = {
+    [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>;
+};
+type ReducerMap = Record<string, Reducer>;
+type ExistingSliceLike<DeclaredState, PreloadedState> = {
+    [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>>;
+}[keyof DeclaredState];
+type InjectConfig = {
+    /**
+     * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
+     */
+    overrideExisting?: boolean;
+};
+/**
+ * A reducer that allows for slices/reducers to be injected after initialisation.
+ */
+interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
+    /**
+     * Provide a type for slices that will be injected lazily.
+     *
+     * One way to do this would be with interface merging:
+     * ```ts
+     *
+     * export interface LazyLoadedSlices {}
+     *
+     * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+     *
+     * // elsewhere
+     *
+     * declare module './reducer' {
+     *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+     * }
+     *
+     * const withBoolean = rootReducer.inject(booleanSlice);
+     *
+     * // elsewhere again
+     *
+     * declare module './reducer' {
+     *   export interface LazyLoadedSlices {
+     *     customName: CustomState
+     *   }
+     * }
+     *
+     * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
+     * ```
+     */
+    withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;
+    /**
+     * Inject a slice.
+     *
+     * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+     *
+     * ```ts
+     * rootReducer.inject(booleanSlice)
+     * rootReducer.inject(baseApi)
+     * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+     * ```
+     *
+     */
+    inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;
+    /**
+     * Inject a slice.
+     *
+     * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+     *
+     * ```ts
+     * rootReducer.inject(booleanSlice)
+     * rootReducer.inject(baseApi)
+     * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+     * ```
+     *
+     */
+    inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;
+    /**
+     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+     *
+     * ```ts
+     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+     * //                                                                ^? boolean | undefined
+     *
+     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+     *   return state.boolean;
+     *   //           ^? boolean
+     * })
+     * ```
+     *
+     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+     *
+     * ```ts
+     *
+     * export interface LazyLoadedSlices {};
+     *
+     * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+     *
+     * export const rootReducer = combineSlices({ inner: innerReducer });
+     *
+     * export type RootState = ReturnType<typeof rootReducer>;
+     *
+     * // elsewhere
+     *
+     * declare module "./reducer.ts" {
+     *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+     * }
+     *
+     * const withBool = innerReducer.inject(booleanSlice);
+     *
+     * const selectBoolean = withBool.selector(
+     *   (state) => state.boolean,
+     *   (rootState: RootState) => state.inner
+     * );
+     * //    now expects to be passed RootState instead of innerReducer state
+     *
+     * ```
+     *
+     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+     *
+     * ```ts
+     * const injectedReducer = rootReducer.inject(booleanSlice);
+     * const selectBoolean = injectedReducer.selector((state) => {
+     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+     *   return state.boolean
+     * })
+     * ```
+     */
+    selector: {
+        /**
+         * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+         *
+         * ```ts
+         * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+         * //                                                                ^? boolean | undefined
+         *
+         * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+         *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+         *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+         *   return state.boolean;
+         *   //           ^? boolean
+         * })
+         * ```
+         *
+         * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+         *
+         * ```ts
+         * const injectedReducer = rootReducer.inject(booleanSlice);
+         * const selectBoolean = injectedReducer.selector((state) => {
+         *   console.log(injectedReducer.selector.original(state).boolean) // undefined
+         *   return state.boolean
+         * })
+         * ```
+         */
+        <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
+        /**
+         * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+         *
+         * ```ts
+         * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+         * //                                                                ^? boolean | undefined
+         *
+         * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+         *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+         *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+         *   return state.boolean;
+         *   //           ^? boolean
+         * })
+         * ```
+         *
+         * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+         *
+         * ```ts
+         *
+         * interface LazyLoadedSlices {};
+         *
+         * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+         *
+         * const rootReducer = combineSlices({ inner: innerReducer });
+         *
+         * type RootState = ReturnType<typeof rootReducer>;
+         *
+         * // elsewhere
+         *
+         * declare module "./reducer.ts" {
+         *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+         * }
+         *
+         * const withBool = innerReducer.inject(booleanSlice);
+         *
+         * const selectBoolean = withBool.selector(
+         *   (state) => state.boolean,
+         *   (rootState: RootState) => state.inner
+         * );
+         * //    now expects to be passed RootState instead of innerReducer state
+         *
+         * ```
+         *
+         * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+         *
+         * ```ts
+         * const injectedReducer = rootReducer.inject(booleanSlice);
+         * const selectBoolean = injectedReducer.selector((state) => {
+         *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+         *   return state.boolean
+         * })
+         * ```
+         */
+        <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
+        /**
+         * Returns the unproxied state. Useful for debugging.
+         * @param state state Proxy, that ensures injected reducers have value
+         * @returns original, unproxied state
+         * @throws if value passed is not a state Proxy
+         */
+        original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;
+    };
+}
+type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;
+type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;
+declare function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>>;
+
+declare const asyncThunkSymbol: unique symbol;
+declare const asyncThunkCreator: {
+    [asyncThunkSymbol]: typeof createAsyncThunk;
+};
+type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
+    reducerPath?: NewReducerPath;
+};
+/**
+ * The return value of `createSlice`
+ *
+ * @public
+ */
+interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
+    /**
+     * The slice name.
+     */
+    name: Name;
+    /**
+     *  The slice reducer path.
+     */
+    reducerPath: ReducerPath;
+    /**
+     * The slice's reducer.
+     */
+    reducer: Reducer<State>;
+    /**
+     * Action creators for the types of actions that are handled by the slice
+     * reducer.
+     */
+    actions: CaseReducerActions<CaseReducers, Name>;
+    /**
+     * The individual case reducer functions that were passed in the `reducers` parameter.
+     * This enables reuse and testing if they were defined inline when calling `createSlice`.
+     */
+    caseReducers: SliceDefinedCaseReducers<CaseReducers>;
+    /**
+     * Provides access to the initial state value given to the slice.
+     * If a lazy state initializer was provided, it will be called and a fresh value returned.
+     */
+    getInitialState: () => State;
+    /**
+     * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+     */
+    getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;
+    /**
+     * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+     */
+    getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
+    /**
+     * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
+     *
+     * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
+     */
+    get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
+        [K in ReducerPath]: State;
+    }>>;
+    /**
+     * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
+     */
+    injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {
+        inject: (slice: {
+            reducerPath: string;
+            reducer: Reducer;
+        }, config?: InjectConfig) => void;
+    }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;
+    /**
+     * Select the slice state, using the slice's current reducerPath.
+     *
+     * Will throw an error if slice is not found.
+     */
+    selectSlice(state: {
+        [K in ReducerPath]: State;
+    }): State;
+}
+/**
+ * A slice after being called with `injectInto(reducer)`.
+ *
+ * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
+ */
+type InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {
+    /**
+     * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+     */
+    getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;
+    /**
+     * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+     */
+    getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
+    /**
+     * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
+     *
+     * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
+     */
+    get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
+        [K in ReducerPath]?: State | undefined;
+    }>>;
+    /**
+     * Select the slice state, using the slice's current reducerPath.
+     *
+     * Returns initial state if slice is not found.
+     */
+    selectSlice(state: {
+        [K in ReducerPath]?: State | undefined;
+    }): State;
+};
+/**
+ * Options for `createSlice()`.
+ *
+ * @public
+ */
+interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
+    /**
+     * The slice's name. Used to namespace the generated action types.
+     */
+    name: Name;
+    /**
+     * The slice's reducer path. Used when injecting into a combined slice reducer.
+     */
+    reducerPath?: ReducerPath;
+    /**
+     * The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+     */
+    initialState: State | (() => State);
+    /**
+     * A mapping from action types to action-type-specific *case reducer*
+     * functions. For every action type, a matching action creator will be
+     * generated using `createAction()`.
+     */
+    reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);
+    /**
+     * A callback that receives a *builder* object to define
+     * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+     *
+     *
+     * @example
+  ```ts
+  import { createAction, createSlice, Action } from '@reduxjs/toolkit'
+  const incrementBy = createAction<number>('incrementBy')
+  const decrement = createAction('decrement')
+  
+  interface RejectedAction extends Action {
+    error: Error
+  }
+  
+  function isRejectedAction(action: Action): action is RejectedAction {
+    return action.type.endsWith('rejected')
+  }
+  
+  createSlice({
+    name: 'counter',
+    initialState: 0,
+    reducers: {},
+    extraReducers: builder => {
+      builder
+        .addCase(incrementBy, (state, action) => {
+          // action is inferred correctly here if using TS
+        })
+        // You can chain calls, or have separate `builder.addCase()` lines each time
+        .addCase(decrement, (state, action) => {})
+        // You can match a range of action types
+        .addMatcher(
+          isRejectedAction,
+          // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
+          (state, action) => {}
+        )
+        // and provide a default case if no other handlers matched
+        .addDefaultCase((state, action) => {})
+      }
+  })
+  ```
+     */
+    extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;
+    /**
+     * A map of selectors that receive the slice's state and any additional arguments, and return a result.
+     */
+    selectors?: Selectors;
+}
+declare enum ReducerType {
+    reducer = "reducer",
+    reducerWithPrepare = "reducerWithPrepare",
+    asyncThunk = "asyncThunk"
+}
+type ReducerDefinition<T extends ReducerType = ReducerType> = {
+    _reducerDefinitionType: T;
+};
+type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;
+/**
+ * A CaseReducer with a `prepare` method.
+ *
+ * @public
+ */
+type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
+    reducer: CaseReducer<State, Action>;
+    prepare: PrepareAction<Action['payload']>;
+};
+type AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
+    options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;
+};
+type AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {
+    payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;
+};
+/**
+ * Providing these as part of the config would cause circular types, so we disallow passing them
+ */
+type PreventCircular<ThunkApiConfig> = {
+    [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K];
+};
+interface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {
+    <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;
+    <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;
+    withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
+}
+interface ReducerCreators<State> {
+    reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;
+    reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;
+    asyncThunk: AsyncThunkCreator<State>;
+    preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {
+        _reducerDefinitionType: ReducerType.reducerWithPrepare;
+        prepare: Prepare;
+        reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;
+    };
+}
+/**
+ * The type describing a slice's `reducers` option.
+ *
+ * @public
+ */
+type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;
+/**
+ * The type describing a slice's `selectors` option.
+ */
+type SliceSelectors<State> = {
+    [K: string]: (sliceState: State, ...args: any[]) => any;
+};
+type SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;
+/**
+ * Derives the slice's `actions` property from the `reducers` options
+ *
+ * @public
+ */
+type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = {
+    [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {
+        prepare: any;
+    } ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {
+        reducer: any;
+    } ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never;
+};
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducerWithPrepare<CR extends {
+    prepare: any;
+}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducer`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (state: any, action: infer Action) => any ? Action extends {
+    payload: infer P;
+} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;
+/**
+ * Extracts the CaseReducers out of a `reducers` object, even if they are
+ * tested into a `CaseReducerWithPrepare`.
+ *
+ * @internal
+ */
+type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
+    [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {
+        reducer: infer Reducer;
+    } ? Reducer : Definition : never;
+};
+type RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {
+    unwrapped: S;
+} : never;
+/**
+ * Extracts the final selector type from the `selectors` object.
+ *
+ * Removes the `string` index signature from the default value.
+ */
+type SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = {
+    [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState>;
+};
+/**
+ * Used on a SliceCaseReducers object.
+ * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
+ * the `reducer` and the `prepare` function use the same type of `payload`.
+ *
+ * Might do additional such checks in the future.
+ *
+ * This type is only ever useful if you want to write your own wrapper around
+ * `createSlice`. Please don't use it otherwise!
+ *
+ * @public
+ */
+type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
+    [T in keyof ACR]: ACR[T] extends {
+        reducer(s: S, action?: infer A): any;
+    } ? {
+        prepare(...a: never[]): Omit<A, 'type'>;
+    } : {};
+};
+interface BuildCreateSliceConfig {
+    creators?: {
+        asyncThunk?: typeof asyncThunkCreator;
+    };
+}
+declare function buildCreateSlice({ creators }?: BuildCreateSliceConfig): <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
+/**
+ * A function that accepts an initial state, an object full of reducer
+ * functions, and a "slice name", and automatically generates
+ * action creators and action types that correspond to the
+ * reducers and state.
+ *
+ * @public
+ */
+declare const createSlice: <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
+
+type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;
+type GetSelectorsOptions = {
+    createSelector?: AnyCreateSelectorFunction;
+};
+
+/**
+ * @public
+ */
+type EntityId = number | string;
+/**
+ * @public
+ */
+type Comparer<T> = (a: T, b: T) => number;
+/**
+ * @public
+ */
+type IdSelector<T, Id extends EntityId> = (model: T) => Id;
+/**
+ * @public
+ */
+type Update<T, Id extends EntityId> = {
+    id: Id;
+    changes: Partial<T>;
+};
+/**
+ * @public
+ */
+interface EntityState<T, Id extends EntityId> {
+    ids: Id[];
+    entities: Record<Id, T>;
+}
+/**
+ * @public
+ */
+interface EntityAdapterOptions<T, Id extends EntityId> {
+    selectId?: IdSelector<T, Id>;
+    sortComparer?: false | Comparer<T>;
+}
+type PreventAny<S, T, Id extends EntityId> = CastAny<S, EntityState<T, Id>>;
+type DraftableEntityState<T, Id extends EntityId> = EntityState<T, Id> | Draft<EntityState<T, Id>>;
+/**
+ * @public
+ */
+interface EntityStateAdapter<T, Id extends EntityId> {
+    addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
+    addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
+    addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+    setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
+    setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
+    setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+    setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+    removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: Id): S;
+    removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: PayloadAction<Id>): S;
+    removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: readonly Id[]): S;
+    removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: PayloadAction<readonly Id[]>): S;
+    removeAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S;
+    updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: Update<T, Id>): S;
+    updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: PayloadAction<Update<T, Id>>): S;
+    updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: ReadonlyArray<Update<T, Id>>): S;
+    updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: PayloadAction<ReadonlyArray<Update<T, Id>>>): S;
+    upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
+    upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: PayloadAction<T>): S;
+    upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+}
+/**
+ * @public
+ */
+interface EntitySelectors<T, V, IdType extends EntityId> {
+    selectIds: (state: V) => IdType[];
+    selectEntities: (state: V) => Record<IdType, T>;
+    selectAll: (state: V) => T[];
+    selectTotal: (state: V) => number;
+    selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>;
+}
+/**
+ * @public
+ */
+interface EntityStateFactory<T, Id extends EntityId> {
+    getInitialState(state?: undefined, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id>;
+    getInitialState<S extends object>(state: S, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id> & S;
+}
+/**
+ * @public
+ */
+interface EntityAdapter<T, Id extends EntityId> extends EntityStateAdapter<T, Id>, EntityStateFactory<T, Id>, Required<EntityAdapterOptions<T, Id>> {
+    getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;
+    getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;
+}
+
+declare function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;
+declare function createEntityAdapter<T extends {
+    id: EntityId;
+}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;
+
+/** @public */
+type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;
+/** @public */
+type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches any one of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+declare function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAnyOf<Matchers>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches all of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+declare function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAllOf<Matchers>;
+type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;
+type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is pending.
+ *
+ * @public
+ */
+declare function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is pending.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a pending thunk action
+ * @public
+ */
+declare function isPending(action: any): action is UnknownAsyncThunkPendingAction;
+type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
+type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected.
+ *
+ * @public
+ */
+declare function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a rejected thunk action
+ * @public
+ */
+declare function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;
+type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {
+    rejectValue: infer RejectedValue;
+}> ? {
+    payload: RejectedValue;
+} : unknown);
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected with value.
+ *
+ * @public
+ */
+declare function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected with value.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a rejected thunk action with value
+ * @public
+ */
+declare function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;
+type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;
+type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is fulfilled.
+ *
+ * @public
+ */
+declare function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is fulfilled.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a fulfilled thunk action
+ * @public
+ */
+declare function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;
+type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;
+type AnyAsyncThunk = {
+    pending: {
+        match: (action: any) => action is any;
+    };
+    fulfilled: {
+        match: (action: any) => action is any;
+    };
+    rejected: {
+        match: (action: any) => action is any;
+    };
+};
+type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator.
+ *
+ * @public
+ */
+declare function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a thunk action
+ * @public
+ */
+declare function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;
+
+/**
+ *
+ * @public
+ */
+declare let nanoid: (size?: number) => string;
+
+declare class TaskAbortError implements SerializedError {
+    code: string | undefined;
+    name: string;
+    message: string;
+    constructor(code: string | undefined);
+}
+
+/**
+ * Types copied from RTK
+ */
+/** @internal */
+type TypedActionCreatorWithMatchFunction<Type extends string> = TypedActionCreator<Type> & {
+    match: MatchFunction<any>;
+};
+/** @internal */
+type AnyListenerPredicate<State> = (action: UnknownAction, currentState: State, originalState: State) => boolean;
+/** @public */
+type ListenerPredicate<ActionType extends Action, State> = (action: UnknownAction, currentState: State, originalState: State) => action is ActionType;
+/** @public */
+interface ConditionFunction<State> {
+    (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
+    (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
+    (predicate: () => boolean, timeout?: number): Promise<boolean>;
+}
+/** @internal */
+type MatchFunction<T> = (v: any) => v is T;
+/** @public */
+interface ForkedTaskAPI {
+    /**
+     * Returns a promise that resolves when `waitFor` resolves or
+     * rejects if the task or the parent listener has been cancelled or is completed.
+     */
+    pause<W>(waitFor: Promise<W>): Promise<W>;
+    /**
+     * Returns a promise that resolves after `timeoutMs` or
+     * rejects if the task or the parent listener has been cancelled or is completed.
+     * @param timeoutMs
+     */
+    delay(timeoutMs: number): Promise<void>;
+    /**
+     * An abort signal whose `aborted` property is set to `true`
+     * if the task execution is either aborted or completed.
+     * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+     */
+    signal: AbortSignal;
+}
+/** @public */
+interface AsyncTaskExecutor<T> {
+    (forkApi: ForkedTaskAPI): Promise<T>;
+}
+/** @public */
+interface SyncTaskExecutor<T> {
+    (forkApi: ForkedTaskAPI): T;
+}
+/** @public */
+type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
+/** @public */
+type TaskResolved<T> = {
+    readonly status: 'ok';
+    readonly value: T;
+};
+/** @public */
+type TaskRejected = {
+    readonly status: 'rejected';
+    readonly error: unknown;
+};
+/** @public */
+type TaskCancelled = {
+    readonly status: 'cancelled';
+    readonly error: TaskAbortError;
+};
+/** @public */
+type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
+/** @public */
+interface ForkedTask<T> {
+    /**
+     * A promise that resolves when the task is either completed or cancelled or rejects
+     * if parent listener execution is cancelled or completed.
+     *
+     * ### Example
+     * ```ts
+     * const result = await fork(async (forkApi) => Promise.resolve(4)).result
+     *
+     * if(result.status === 'ok') {
+     *   console.log(result.value) // logs 4
+     * }}
+     * ```
+     */
+    result: Promise<TaskResult<T>>;
+    /**
+     * Cancel task if it is in progress or not yet started,
+     * it is noop otherwise.
+     */
+    cancel(): void;
+}
+/** @public */
+interface ForkOptions {
+    /**
+     * If true, causes the parent task to not be marked as complete until
+     * all autoJoined forks have completed or failed.
+     */
+    autoJoin: boolean;
+}
+/** @public */
+interface ListenerEffectAPI<State, DispatchType extends Dispatch, ExtraArgument = unknown> extends MiddlewareAPI<DispatchType, State> {
+    /**
+     * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
+     *
+     * ### Synchronous invocation
+     *
+     * This function can **only** be invoked **synchronously**, it throws error otherwise.
+     *
+     * @example
+     *
+     * ```ts
+     * middleware.startListening({
+     *  predicate: () => true,
+     *  async effect(_, { getOriginalState }) {
+     *    getOriginalState(); // sync: OK!
+     *
+     *    setTimeout(getOriginalState, 0); // async: throws Error
+     *
+     *    await Promise().resolve();
+     *
+     *    getOriginalState() // async: throws Error
+     *  }
+     * })
+     * ```
+     */
+    getOriginalState: () => State;
+    /**
+     * Removes the listener entry from the middleware and prevent future instances of the listener from running.
+     *
+     * It does **not** cancel any active instances.
+     */
+    unsubscribe(): void;
+    /**
+     * It will subscribe a listener if it was previously removed, noop otherwise.
+     */
+    subscribe(): void;
+    /**
+     * Returns a promise that resolves when the input predicate returns `true` or
+     * rejects if the listener has been cancelled or is completed.
+     *
+     * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
+     *
+     * ### Example
+     *
+     * ```ts
+     * const updateBy = createAction<number>('counter/updateBy');
+     *
+     * middleware.startListening({
+     *  actionCreator: updateBy,
+     *  async effect(_, { condition }) {
+     *    // wait at most 3s for `updateBy` actions.
+     *    if(await condition(updateBy.match, 3_000)) {
+     *      // `updateBy` has been dispatched twice in less than 3s.
+     *    }
+     *  }
+     * })
+     * ```
+     */
+    condition: ConditionFunction<State>;
+    /**
+     * Returns a promise that resolves when the input predicate returns `true` or
+     * rejects if the listener has been cancelled or is completed.
+     *
+     * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
+     *
+     * The promise resolves to null if a timeout is provided and expires first,
+     *
+     * ### Example
+     *
+     * ```ts
+     * const updateBy = createAction<number>('counter/updateBy');
+     *
+     * middleware.startListening({
+     *  actionCreator: updateBy,
+     *  async effect(_, { take }) {
+     *    const [{ payload }] =  await take(updateBy.match);
+     *    console.log(payload); // logs 5;
+     *  }
+     * })
+     *
+     * store.dispatch(updateBy(5));
+     * ```
+     */
+    take: TakePattern<State>;
+    /**
+     * Cancels all other running instances of this same listener except for the one that made this call.
+     */
+    cancelActiveListeners: () => void;
+    /**
+     * Cancels the instance of this listener that made this call.
+     */
+    cancel: () => void;
+    /**
+     * Throws a `TaskAbortError` if this listener has been cancelled
+     */
+    throwIfCancelled: () => void;
+    /**
+     * An abort signal whose `aborted` property is set to `true`
+     * if the listener execution is either aborted or completed.
+     * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+     */
+    signal: AbortSignal;
+    /**
+     * Returns a promise that resolves after `timeoutMs` or
+     * rejects if the listener has been cancelled or is completed.
+     */
+    delay(timeoutMs: number): Promise<void>;
+    /**
+     * Queues in the next microtask the execution of a task.
+     * @param executor
+     * @param options
+     */
+    fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>;
+    /**
+     * Returns a promise that resolves when `waitFor` resolves or
+     * rejects if the listener has been cancelled or is completed.
+     * @param promise
+     */
+    pause<M>(promise: Promise<M>): Promise<M>;
+    extra: ExtraArgument;
+}
+/** @public */
+type ListenerEffect<ActionType extends Action, State, DispatchType extends Dispatch, ExtraArgument = unknown> = (action: ActionType, api: ListenerEffectAPI<State, DispatchType, ExtraArgument>) => void | Promise<void>;
+/**
+ * @public
+ * Additional infos regarding the error raised.
+ */
+interface ListenerErrorInfo {
+    /**
+     * Which function has generated the exception.
+     */
+    raisedBy: 'effect' | 'predicate';
+}
+/**
+ * @public
+ * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
+ * @param error The thrown error.
+ * @param errorInfo Additional information regarding the thrown error.
+ */
+interface ListenerErrorHandler {
+    (error: unknown, errorInfo: ListenerErrorInfo): void;
+}
+/** @public */
+interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
+    extra?: ExtraArgument;
+    /**
+     * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
+     */
+    onError?: ListenerErrorHandler;
+}
+/** @public */
+type ListenerMiddleware<State = unknown, DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<State, unknown, UnknownAction>, ExtraArgument = unknown> = Middleware<{
+    (action: Action<'listenerMiddleware/add'>): UnsubscribeListener;
+}, State, DispatchType>;
+/** @public */
+interface ListenerMiddlewareInstance<StateType = unknown, DispatchType extends ThunkDispatch<StateType, unknown, Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> {
+    middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>;
+    startListening: AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & TypedStartListening<StateType, DispatchType, ExtraArgument>;
+    stopListening: RemoveListenerOverloads<StateType, DispatchType> & TypedStopListening<StateType, DispatchType>;
+    /**
+     * Unsubscribes all listeners, cancels running listeners and tasks.
+     */
+    clearListeners: () => void;
+}
+/**
+ * API Function Overloads
+ */
+/** @public */
+type TakePatternOutputWithoutTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State]> : Promise<[UnknownAction, State, State]>;
+/** @public */
+type TakePatternOutputWithTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State] | null> : Promise<[UnknownAction, State, State] | null>;
+/** @public */
+interface TakePattern<State> {
+    <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate): TakePatternOutputWithoutTimeout<State, Predicate>;
+    <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout: number): TakePatternOutputWithTimeout<State, Predicate>;
+    <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout?: number | undefined): TakePatternOutputWithTimeout<State, Predicate>;
+}
+/** @public */
+interface UnsubscribeListenerOptions {
+    cancelActive?: true;
+}
+/** @public */
+type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
+/**
+ * @public
+ * The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
+ */
+type AddListenerOverloads<Return, StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, AdditionalOptions = unknown> = {
+    /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
+    <MiddlewareActionType extends UnknownAction, ListenerPredicateType extends ListenerPredicate<MiddlewareActionType, StateType>>(options: {
+        actionCreator?: never;
+        type?: never;
+        matcher?: never;
+        predicate: ListenerPredicateType;
+        effect: ListenerEffect<ListenerPredicateGuardedActionType<ListenerPredicateType>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts an RTK action creator, like `incrementByAmount` */
+    <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(options: {
+        actionCreator: ActionCreatorType;
+        type?: never;
+        matcher?: never;
+        predicate?: never;
+        effect: ListenerEffect<ReturnType<ActionCreatorType>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts a specific action type string */
+    <T extends string>(options: {
+        actionCreator?: never;
+        type: T;
+        matcher?: never;
+        predicate?: never;
+        effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
+    <MatchFunctionType extends MatchFunction<UnknownAction>>(options: {
+        actionCreator?: never;
+        type?: never;
+        matcher: MatchFunctionType;
+        predicate?: never;
+        effect: ListenerEffect<GuardedType<MatchFunctionType>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
+    <ListenerPredicateType extends AnyListenerPredicate<StateType>>(options: {
+        actionCreator?: never;
+        type?: never;
+        matcher?: never;
+        predicate: ListenerPredicateType;
+        effect: ListenerEffect<UnknownAction, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+};
+/** @public */
+type RemoveListenerOverloads<StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<boolean, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions>;
+/**
+ * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedAddListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/add'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument> & {
+    /**
+     * Creates a "pre-typed" version of `addListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `addListener` call.
+     *
+     * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { addListener } from '@reduxjs/toolkit'
+     *
+     * export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedAddListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedRemoveListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/remove'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions> & {
+    /**
+     * Creates a "pre-typed" version of `removeListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `removeListener` call.
+     *
+     * @returns A pre-typed `removeListener` with the state, dispatch and extra
+     * types already defined.
+     *
+     * @example
+     * ```ts
+     * import { removeListener } from '@reduxjs/toolkit'
+     *
+     * export const removeAppListener = removeListener.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedRemoveListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedStartListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & {
+    /**
+     * Creates a "pre-typed" version of
+     * {@linkcode ListenerMiddlewareInstance.startListening startListening}
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every
+     * {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
+     *
+     * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { createListenerMiddleware } from '@reduxjs/toolkit'
+     *
+     * const listenerMiddleware = createListenerMiddleware()
+     *
+     * export const startAppListening = listenerMiddleware.startListening.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStartListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedStopListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
+    /**
+     * Creates a "pre-typed" version of
+     * {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every
+     * {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
+     *
+     * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { createListenerMiddleware } from '@reduxjs/toolkit'
+     *
+     * const listenerMiddleware = createListenerMiddleware()
+     *
+     * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * Internal Types
+ */
+/** @internal An single listener entry */
+type ListenerEntry<State = unknown, DispatchType extends Dispatch = Dispatch> = {
+    id: string;
+    effect: ListenerEffect<any, State, DispatchType>;
+    unsubscribe: () => void;
+    pending: Set<AbortController>;
+    type?: string;
+    predicate: ListenerPredicate<UnknownAction, State>;
+};
+/**
+ * Utility Types
+ */
+/** @public */
+type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T ? T : never;
+/** @public */
+type ListenerPredicateGuardedActionType<T> = T extends ListenerPredicate<infer ActionType, any> ? ActionType : never;
+
+/**
+ * @public
+ */
+declare const addListener: TypedAddListener<unknown>;
+/**
+ * @public
+ */
+declare const clearAllListeners: ActionCreatorWithoutPayload<"listenerMiddleware/removeAll">;
+/**
+ * @public
+ */
+declare const removeListener: TypedRemoveListener<unknown>;
+/**
+ * @public
+ */
+declare const createListenerMiddleware: <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>) => ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;
+
+type MiddlewareApiConfig = {
+    state?: unknown;
+    dispatch?: Dispatch;
+};
+type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
+    dispatch: infer DispatchType;
+} ? FallbackIfUnknown<DispatchType, Dispatch> : Dispatch;
+type AddMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
+    (...middlewares: Middleware<any, State, DispatchType>[]): void;
+    withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
+};
+type WithMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = BaseActionCreator<Middleware<any, State, DispatchType>[], 'dynamicMiddleware/add', {
+    instanceId: string;
+}> & {
+    <Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares): PayloadAction<Middlewares, 'dynamicMiddleware/add', {
+        instanceId: string;
+    }>;
+    withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
+};
+interface DynamicDispatch {
+    <Middlewares extends Middleware<any>[]>(action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>): ExtractDispatchExtensions<Middlewares> & this;
+}
+type DynamicMiddleware<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = Middleware<DynamicDispatch, State, DispatchType>;
+type DynamicMiddlewareInstance<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
+    middleware: DynamicMiddleware<State, DispatchType>;
+    addMiddleware: AddMiddleware<State, DispatchType>;
+    withMiddleware: WithMiddleware<State, DispatchType>;
+    instanceId: string;
+};
+
+declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => DynamicMiddlewareInstance<State, DispatchType>;
+
+/**
+ * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
+ *
+ * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
+ * during build.
+ * @param {number} code
+ */
+declare function formatProdErrorMessage(code: number): string;
+
+export { type ActionCreatorInvariantMiddlewareOptions, type ActionCreatorWithNonInferrablePayload, type ActionCreatorWithOptionalPayload, type ActionCreatorWithPayload, type ActionCreatorWithPreparedPayload, type ActionCreatorWithoutPayload, type ActionMatchingAllOf, type ActionMatchingAnyOf, type ActionReducerMapBuilder, type Actions, type AddMiddleware, type AnyListenerPredicate, type AsyncTaskExecutor, type AsyncThunk, type AsyncThunkAction, type AsyncThunkConfig, type AsyncThunkDispatchConfig, type AsyncThunkOptions, type AsyncThunkPayloadCreator, type AsyncThunkPayloadCreatorReturnValue, type AsyncThunkReducers, type AutoBatchOptions, type CaseReducer, type CaseReducerActions, type CaseReducerWithPrepare, type CaseReducers, type CombinedSliceReducer, type Comparer, type ConfigureStoreOptions, type CreateAsyncThunkFunction, type CreateListenerMiddlewareOptions, type CreateSliceOptions, type DevToolsEnhancerOptions, type DynamicDispatch, type DynamicMiddlewareInstance, type EnhancedStore, type EntityAdapter, type EntityId, type EntitySelectors, type EntityState, type EntityStateAdapter, type ForkedTask, type ForkedTaskAPI, type ForkedTaskExecutor, type GetDispatchType as GetDispatch, type GetState, type GetThunkAPI, type IdSelector, type ImmutableStateInvariantMiddlewareOptions, type ListenerEffect, type ListenerEffectAPI, type ListenerErrorHandler, type ListenerMiddleware, type ListenerMiddlewareInstance, type MiddlewareApiConfig, type PayloadAction, type PayloadActionCreator, type PrepareAction, type ReducerCreators, ReducerType, SHOULD_AUTOBATCH, type SafePromise, type SerializableStateInvariantMiddlewareOptions, type SerializedError, type Slice, type SliceCaseReducers, type SliceSelectors, type SyncTaskExecutor, type ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, TaskAbortError, type TaskCancelled, type TaskRejected, type TaskResolved, type TaskResult, Tuple, type TypedAddListener, type TypedRemoveListener, type TypedStartListening, type TypedStopListening, type UnsubscribeListener, type UnsubscribeListenerOptions, type Update, type ValidateSliceCaseReducers, type WithSlice, type WithSlicePreloadedState, addListener, asyncThunkCreator, autoBatchEnhancer, buildCreateSlice, clearAllListeners, combineSlices, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, createReducer, createSerializableStateInvariantMiddleware, createSlice, findNonSerializableValue, formatProdErrorMessage, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isRejected, isRejectedWithValue, miniSerializeError, nanoid, prepareAutoBatched, removeListener, unwrapResult };
Index: node_modules/@reduxjs/toolkit/dist/index.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2662 @@
+import { ActionCreator, Action, Middleware, StoreEnhancer, UnknownAction, Reducer, ReducersMapObject, Store, Dispatch, StateFromReducersMapObject, PreloadedStateShapeFromReducersMapObject, MiddlewareAPI } from 'redux';
+export * from 'redux';
+import { Draft } from 'immer';
+export { Draft, WritableDraft, produce as createNextState, current, freeze, isDraft, original } from 'immer';
+import * as reselect from 'reselect';
+import { weakMapMemoize, createSelectorCreator, Selector, CreateSelectorFunction } from 'reselect';
+export { OutputSelector, Selector, createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from 'reselect';
+import { ThunkMiddleware, ThunkDispatch } from 'redux-thunk';
+export { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';
+import { UncheckedIndexedAccess } from './uncheckedindexed.js';
+
+declare const createDraftSafeSelectorCreator: typeof createSelectorCreator;
+/**
+ * "Draft-Safe" version of `reselect`'s `createSelector`:
+ * If an `immer`-drafted object is passed into the resulting selector's first argument,
+ * the selector will act on the current draft value, instead of returning a cached value
+ * that might be possibly outdated if the draft has been modified since.
+ * @public
+ */
+declare const createDraftSafeSelector: reselect.CreateSelectorFunction<typeof weakMapMemoize, typeof weakMapMemoize, any>;
+
+/**
+ * @public
+ */
+interface DevToolsEnhancerOptions {
+    /**
+     * the instance name to be showed on the monitor page. Default value is `document.title`.
+     * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
+     */
+    name?: string;
+    /**
+     * action creators functions to be available in the Dispatcher.
+     */
+    actionCreators?: ActionCreator<any>[] | {
+        [key: string]: ActionCreator<any>;
+    };
+    /**
+     * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
+     * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
+     * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
+     *
+     * @default 500 ms.
+     */
+    latency?: number;
+    /**
+     * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
+     *
+     * @default 50
+     */
+    maxAge?: number;
+    /**
+     * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
+     * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
+     * functions.
+     */
+    serialize?: boolean | {
+        /**
+         * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
+         * - `false` - will handle also circular references.
+         * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
+         * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
+         *   For each of them you can indicate if to include (by setting as `true`).
+         *   For `function` key you can also specify a custom function which handles serialization.
+         *   See [`jsan`](https://github.com/kolodny/jsan) for more details.
+         */
+        options?: undefined | boolean | {
+            date?: true;
+            regex?: true;
+            undefined?: true;
+            error?: true;
+            symbol?: true;
+            map?: true;
+            set?: true;
+            function?: true | ((fn: (...args: any[]) => any) => string);
+        };
+        /**
+         * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
+         * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
+         * key. So you can deserialize it back while importing or persisting data.
+         * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
+         */
+        replacer?: (key: string, value: unknown) => any;
+        /**
+         * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
+         * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
+         * as an example on how to serialize special data types and get them back.
+         */
+        reviver?: (key: string, value: unknown) => any;
+        /**
+         * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
+         * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
+         * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
+         */
+        immutable?: any;
+        /**
+         * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
+         */
+        refs?: any;
+    };
+    /**
+     * function which takes `action` object and id number as arguments, and should return `action` object back.
+     */
+    actionSanitizer?: <A extends Action>(action: A, id: number) => A;
+    /**
+     * function which takes `state` object and index as arguments, and should return `state` object back.
+     */
+    stateSanitizer?: <S>(state: S, index: number) => S;
+    /**
+     * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+     * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+     */
+    actionsDenylist?: string | string[];
+    /**
+     * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+     * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+     */
+    actionsAllowlist?: string | string[];
+    /**
+     * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
+     * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
+     */
+    predicate?: <S, A extends Action>(state: S, action: A) => boolean;
+    /**
+     * if specified as `false`, it will not record the changes till clicking on `Start recording` button.
+     * Available only for Redux enhancer, for others use `autoPause`.
+     *
+     * @default true
+     */
+    shouldRecordChanges?: boolean;
+    /**
+     * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
+     * If not specified, will commit when paused. Available only for Redux enhancer.
+     *
+     * @default "@@PAUSED""
+     */
+    pauseActionType?: string;
+    /**
+     * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
+     * Not available for Redux enhancer (as it already does it but storing the data to be sent).
+     *
+     * @default false
+     */
+    autoPause?: boolean;
+    /**
+     * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
+     * Available only for Redux enhancer.
+     *
+     * @default false
+     */
+    shouldStartLocked?: boolean;
+    /**
+     * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
+     *
+     * @default true
+     */
+    shouldHotReload?: boolean;
+    /**
+     * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
+     *
+     * @default false
+     */
+    shouldCatchErrors?: boolean;
+    /**
+     * If you want to restrict the extension, specify the features you allow.
+     * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
+     * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
+     * Otherwise, you'll get/set the data right from the monitor part.
+     */
+    features?: {
+        /**
+         * start/pause recording of dispatched actions
+         */
+        pause?: boolean;
+        /**
+         * lock/unlock dispatching actions and side effects
+         */
+        lock?: boolean;
+        /**
+         * persist states on page reloading
+         */
+        persist?: boolean;
+        /**
+         * export history of actions in a file
+         */
+        export?: boolean | 'custom';
+        /**
+         * import history of actions from a file
+         */
+        import?: boolean | 'custom';
+        /**
+         * jump back and forth (time travelling)
+         */
+        jump?: boolean;
+        /**
+         * skip (cancel) actions
+         */
+        skip?: boolean;
+        /**
+         * drag and drop actions in the history list
+         */
+        reorder?: boolean;
+        /**
+         * dispatch custom actions or action creators
+         */
+        dispatch?: boolean;
+        /**
+         * generate tests for the selected actions
+         */
+        test?: boolean;
+    };
+    /**
+     * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
+     * Defaults to false.
+     */
+    trace?: boolean | (<A extends Action>(action: A) => string);
+    /**
+     * The maximum number of stack trace entries to record per action. Defaults to 10.
+     */
+    traceLimit?: number;
+}
+
+interface ActionCreatorInvariantMiddlewareOptions {
+    /**
+     * The function to identify whether a value is an action creator.
+     * The default checks for a function with a static type property and match method.
+     */
+    isActionCreator?: (action: unknown) => action is Function & {
+        type?: unknown;
+    };
+}
+declare function createActionCreatorInvariantMiddleware(options?: ActionCreatorInvariantMiddlewareOptions): Middleware;
+
+/**
+ * Returns true if the passed value is "plain", i.e. a value that is either
+ * directly JSON-serializable (boolean, number, string, array, plain object)
+ * or `undefined`.
+ *
+ * @param val The value to check.
+ *
+ * @public
+ */
+declare function isPlain(val: any): boolean;
+interface NonSerializableValue {
+    keyPath: string;
+    value: unknown;
+}
+type IgnorePaths = readonly (string | RegExp)[];
+/**
+ * @public
+ */
+declare function findNonSerializableValue(value: unknown, path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], ignoredPaths?: IgnorePaths, cache?: WeakSet<object>): NonSerializableValue | false;
+/**
+ * Options for `createSerializableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+interface SerializableStateInvariantMiddlewareOptions {
+    /**
+     * The function to check if a value is considered serializable. This
+     * function is applied recursively to every value contained in the
+     * state. Defaults to `isPlain()`.
+     */
+    isSerializable?: (value: any) => boolean;
+    /**
+     * The function that will be used to retrieve entries from each
+     * value.  If unspecified, `Object.entries` will be used. Defaults
+     * to `undefined`.
+     */
+    getEntries?: (value: any) => [string, any][];
+    /**
+     * An array of action types to ignore when checking for serializability.
+     * Defaults to []
+     */
+    ignoredActions?: string[];
+    /**
+     * An array of dot-separated path strings or regular expressions to ignore
+     * when checking for serializability, Defaults to
+     * ['meta.arg', 'meta.baseQueryMeta']
+     */
+    ignoredActionPaths?: (string | RegExp)[];
+    /**
+     * An array of dot-separated path strings or regular expressions to ignore
+     * when checking for serializability, Defaults to []
+     */
+    ignoredPaths?: (string | RegExp)[];
+    /**
+     * Execution time warning threshold. If the middleware takes longer
+     * than `warnAfter` ms, a warning will be displayed in the console.
+     * Defaults to 32ms.
+     */
+    warnAfter?: number;
+    /**
+     * Opt out of checking state. When set to `true`, other state-related params will be ignored.
+     */
+    ignoreState?: boolean;
+    /**
+     * Opt out of checking actions. When set to `true`, other action-related params will be ignored.
+     */
+    ignoreActions?: boolean;
+    /**
+     * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.
+     * The cache is automatically disabled if no browser support for WeakSet is present.
+     */
+    disableCache?: boolean;
+}
+/**
+ * Creates a middleware that, after every state change, checks if the new
+ * state is serializable. If a non-serializable value is found within the
+ * state, an error is printed to the console.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+declare function createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware;
+
+/**
+ * The default `isImmutable` function.
+ *
+ * @public
+ */
+declare function isImmutableDefault(value: unknown): boolean;
+type IsImmutableFunc = (value: any) => boolean;
+/**
+ * Options for `createImmutableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+interface ImmutableStateInvariantMiddlewareOptions {
+    /**
+      Callback function to check if a value is considered to be immutable.
+      This function is applied recursively to every value contained in the state.
+      The default implementation will return true for primitive types
+      (like numbers, strings, booleans, null and undefined).
+     */
+    isImmutable?: IsImmutableFunc;
+    /**
+      An array of dot-separated path strings that match named nodes from
+      the root state to ignore when checking for immutability.
+      Defaults to undefined
+     */
+    ignoredPaths?: IgnorePaths;
+    /** Print a warning if checks take longer than N ms. Default: 32ms */
+    warnAfter?: number;
+}
+/**
+ * Creates a middleware that checks whether any state was mutated in between
+ * dispatches or during a dispatch. If any mutations are detected, an error is
+ * thrown.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+declare function createImmutableStateInvariantMiddleware(options?: ImmutableStateInvariantMiddlewareOptions): Middleware;
+
+declare class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {
+    constructor(length: number);
+    constructor(...items: Items);
+    static get [Symbol.species](): any;
+    concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;
+    concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
+    concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
+    prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;
+    prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
+    prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
+}
+
+/**
+ * return True if T is `any`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
+type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
+/**
+ * return True if T is `unknown`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;
+type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;
+/**
+ * @internal
+ */
+type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;
+/**
+ * @internal
+ */
+type IfVoid<P, True, False> = [void] extends [P] ? True : False;
+/**
+ * @internal
+ */
+type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;
+/**
+ * returns True if TS version is above 3.5, False if below.
+ * uses feature detection to detect TS version >= 3.5
+ * * versions below 3.5 will return `{}` for unresolvable interference
+ * * versions above will return `unknown`
+ *
+ * @internal
+ */
+type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<(<T>() => T)>, 0, 1>];
+/**
+ * @internal
+ */
+type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
+type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
+    infer Head,
+    ...infer Tail
+] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;
+type ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;
+type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;
+type ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;
+type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;
+type ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;
+type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;
+/**
+ * Helper type. Passes T out again, but boxes it in a way that it cannot
+ * "widen" the type by accident if it is a generic that should be inferred
+ * from elsewhere.
+ *
+ * @internal
+ */
+type NoInfer<T> = [T][T extends any ? 0 : never];
+type NonUndefined<T> = T extends undefined ? never : T;
+type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
+type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
+interface TypeGuard<T> {
+    (value: any): value is T;
+}
+interface HasMatchFunction<T> {
+    match: TypeGuard<T>;
+}
+/** @public */
+type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;
+/** @public */
+type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;
+type Id<T> = {
+    [K in keyof T]: T[K];
+} & {};
+type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;
+type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;
+/**
+ * A Promise that will never reject.
+ * @see https://github.com/reduxjs/redux-toolkit/issues/4101
+ */
+type SafePromise<T> = Promise<T> & {
+    __linterBrands: 'SafePromise';
+};
+
+interface ThunkOptions<E = any> {
+    extraArgument: E;
+}
+interface GetDefaultMiddlewareOptions {
+    thunk?: boolean | ThunkOptions;
+    immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;
+    serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;
+    actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;
+}
+type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {
+    thunk: false;
+} ? never : O extends {
+    thunk: {
+        extraArgument: infer E;
+    };
+} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;
+type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {
+    thunk: true;
+    immutableCheck: true;
+    serializableCheck: true;
+    actionCreatorCheck: true;
+}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
+
+declare const SHOULD_AUTOBATCH = "RTK_autoBatch";
+declare const prepareAutoBatched: <T>() => (payload: T) => {
+    payload: T;
+    meta: unknown;
+};
+type AutoBatchOptions = {
+    type: 'tick';
+} | {
+    type: 'timer';
+    timeout: number;
+} | {
+    type: 'raf';
+} | {
+    type: 'callback';
+    queueNotification: (notify: () => void) => void;
+};
+/**
+ * A Redux store enhancer that watches for "low-priority" actions, and delays
+ * notifying subscribers until either the queued callback executes or the
+ * next "standard-priority" action is dispatched.
+ *
+ * This allows dispatching multiple "low-priority" actions in a row with only
+ * a single subscriber notification to the UI after the sequence of actions
+ * is finished, thus improving UI re-render performance.
+ *
+ * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
+ * This can be added to `action.meta` manually, or by using the
+ * `prepareAutoBatched` helper.
+ *
+ * By default, it will queue a notification for the end of the event loop tick.
+ * However, you can pass several other options to configure the behavior:
+ * - `{type: 'tick'}`: queues using `queueMicrotask`
+ * - `{type: 'timer', timeout: number}`: queues using `setTimeout`
+ * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
+ * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
+ *
+ *
+ */
+declare const autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;
+
+type GetDefaultEnhancersOptions = {
+    autoBatch?: boolean | AutoBatchOptions;
+};
+type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{
+    dispatch: ExtractDispatchExtensions<M>;
+}>]>;
+
+/**
+ * Options for `configureStore()`.
+ *
+ * @public
+ */
+interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {
+    /**
+     * A single reducer function that will be used as the root reducer, or an
+     * object of slice reducers that will be passed to `combineReducers()`.
+     */
+    reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;
+    /**
+     * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
+     * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
+     *
+     * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
+     * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
+     */
+    middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;
+    /**
+     * Whether to enable Redux DevTools integration. Defaults to `true`.
+     *
+     * Additional configuration can be done by passing Redux DevTools options
+     */
+    devTools?: boolean | DevToolsEnhancerOptions;
+    /**
+     * Whether to check for duplicate middleware instances. Defaults to `true`.
+     */
+    duplicateMiddlewareCheck?: boolean;
+    /**
+     * The initial state, same as Redux's createStore.
+     * You may optionally specify it to hydrate the state
+     * from the server in universal apps, or to restore a previously serialized
+     * user session. If you use `combineReducers()` to produce the root reducer
+     * function (either directly or indirectly by passing an object as `reducer`),
+     * this must be an object with the same shape as the reducer map keys.
+     */
+    preloadedState?: P;
+    /**
+     * The store enhancers to apply. See Redux's `createStore()`.
+     * All enhancers will be included before the DevTools Extension enhancer.
+     * If you need to customize the order of enhancers, supply a callback
+     * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
+     * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
+     * If you only need to add middleware, you can use the `middleware` parameter instead.
+     */
+    enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;
+}
+type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;
+type Enhancers = ReadonlyArray<StoreEnhancer>;
+/**
+ * A Redux store returned by `configureStore()`. Supports dispatching
+ * side-effectful _thunks_ in addition to plain actions.
+ *
+ * @public
+ */
+type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;
+/**
+ * A friendly abstraction over the standard Redux `createStore()` function.
+ *
+ * @param options The store configuration.
+ * @returns A configured Redux store.
+ *
+ * @public
+ */
+declare function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[
+    StoreEnhancer<{
+        dispatch: ExtractDispatchExtensions<M>;
+    }>,
+    StoreEnhancer
+]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E>;
+
+/**
+ * An action with a string type and an associated payload. This is the
+ * type of action returned by `createAction()` action creators.
+ *
+ * @template P The type of the action's payload.
+ * @template T the type used for the action type.
+ * @template M The type of the action's meta (optional)
+ * @template E The type of the action's error (optional)
+ *
+ * @public
+ */
+type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
+    payload: P;
+    type: T;
+} & ([M] extends [never] ? {} : {
+    meta: M;
+}) & ([E] extends [never] ? {} : {
+    error: E;
+});
+/**
+ * A "prepare" method to be used as the second parameter of `createAction`.
+ * Takes any number of arguments and returns a Flux Standard Action without
+ * type (will be added later) that *must* contain a payload (might be undefined).
+ *
+ * @public
+ */
+type PrepareAction<P> = ((...args: any[]) => {
+    payload: P;
+}) | ((...args: any[]) => {
+    payload: P;
+    meta: any;
+}) | ((...args: any[]) => {
+    payload: P;
+    error: any;
+}) | ((...args: any[]) => {
+    payload: P;
+    meta: any;
+    error: any;
+});
+/**
+ * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
+ *
+ * @internal
+ */
+type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {
+    error: infer E;
+} ? E : never, ReturnType<PA> extends {
+    meta: infer M;
+} ? M : never> : void;
+/**
+ * Basic type for all action creators.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ */
+type BaseActionCreator<P, T extends string, M = never, E = never> = {
+    type: T;
+    match: (action: unknown) => action is PayloadAction<P, T, M, E>;
+};
+/**
+ * An action creator that takes multiple arguments that are passed
+ * to a `PrepareAction` method to create the final Action.
+ * @typeParam Args arguments for the action creator function
+ * @typeParam P `payload` type
+ * @typeParam T `type` name
+ * @typeParam E optional `error` type
+ * @typeParam M optional `meta` type
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
+    /**
+     * Calling this {@link redux#ActionCreator} with `Args` will return
+     * an Action with a payload of type `P` and (depending on the `PrepareAction`
+     * method used) a `meta`- and `error` property of types `M` and `E` respectively.
+     */
+    (...args: Args): PayloadAction<P, T, M, E>;
+}
+/**
+ * An action creator of type `T` that takes an optional payload of type `P`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} with an argument will
+     * return a {@link PayloadAction} of type `T` with a payload of `P`.
+     * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
+     */
+    (payload?: P): PayloadAction<P, T>;
+}
+/**
+ * An action creator of type `T` that takes no payload.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} will
+     * return a {@link PayloadAction} of type `T` with a payload of `undefined`
+     */
+    (noArgument: void): PayloadAction<undefined, T>;
+}
+/**
+ * An action creator of type `T` that requires a payload of type P.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} with an argument will
+     * return a {@link PayloadAction} of type `T` with a payload of `P`
+     */
+    (payload: P): PayloadAction<P, T>;
+}
+/**
+ * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
+    /**
+     * Calling this {@link redux#ActionCreator} with an argument will
+     * return a {@link PayloadAction} of type `T` with a payload
+     * of exactly the type of the argument.
+     */
+    <PT extends unknown>(payload: PT): PayloadAction<PT, T>;
+}
+/**
+ * An action creator that produces actions with a `payload` attribute.
+ *
+ * @typeParam P the `payload` type
+ * @typeParam T the `type` of the resulting action
+ * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
+ *
+ * @public
+ */
+type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>, IfVoid<P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T>>>>>>;
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;
+/**
+ * Returns true if value is an RTK-like action creator, with a static type property and match method.
+ */
+declare function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function;
+/**
+ * Returns true if value is an action with a string type and valid Flux Standard Action keys.
+ */
+declare function isFSA(action: unknown): action is {
+    type: string;
+    payload?: unknown;
+    error?: unknown;
+    meta?: unknown;
+};
+type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
+
+type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {
+    dispatch: D;
+    getState: () => S;
+    extra: E;
+    requestId: string;
+    signal: AbortSignal;
+    abort: (reason?: string) => void;
+    rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;
+    fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;
+};
+/**
+ * @public
+ */
+interface SerializedError {
+    name?: string;
+    message?: string;
+    stack?: string;
+    code?: string;
+}
+declare class RejectWithValue<Payload, RejectedMeta> {
+    readonly payload: Payload;
+    readonly meta: RejectedMeta;
+    private readonly _type;
+    constructor(payload: Payload, meta: RejectedMeta);
+}
+declare class FulfillWithMeta<Payload, FulfilledMeta> {
+    readonly payload: Payload;
+    readonly meta: FulfilledMeta;
+    private readonly _type;
+    constructor(payload: Payload, meta: FulfilledMeta);
+}
+/**
+ * Serializes an error into a plain object.
+ * Reworked from https://github.com/sindresorhus/serialize-error
+ *
+ * @public
+ */
+declare const miniSerializeError: (value: any) => SerializedError;
+type AsyncThunkConfig = {
+    state?: unknown;
+    dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;
+    extra?: unknown;
+    rejectValue?: unknown;
+    serializedErrorType?: unknown;
+    pendingMeta?: unknown;
+    fulfilledMeta?: unknown;
+    rejectedMeta?: unknown;
+};
+type GetState<ThunkApiConfig> = ThunkApiConfig extends {
+    state: infer State;
+} ? State : unknown;
+type GetExtra<ThunkApiConfig> = ThunkApiConfig extends {
+    extra: infer Extra;
+} ? Extra : unknown;
+type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
+    dispatch: infer Dispatch;
+} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;
+type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;
+type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
+    rejectValue: infer RejectValue;
+} ? RejectValue : unknown;
+type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
+    pendingMeta: infer PendingMeta;
+} ? PendingMeta : unknown;
+type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
+    fulfilledMeta: infer FulfilledMeta;
+} ? FulfilledMeta : unknown;
+type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
+    rejectedMeta: infer RejectedMeta;
+} ? RejectedMeta : unknown;
+type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
+    serializedErrorType: infer GetSerializedErrorType;
+} ? GetSerializedErrorType : SerializedError;
+type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);
+/**
+ * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;
+/**
+ * A type describing the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
+/**
+ * A ThunkAction created by `createAsyncThunk`.
+ * Dispatching it returns a Promise for either a
+ * fulfilled or rejected action.
+ * Also, the returned value contains an `abort()` method
+ * that allows the asyncAction to be cancelled from the outside.
+ *
+ * @public
+ */
+type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {
+    abort: (reason?: string) => void;
+    requestId: string;
+    arg: ThunkArg;
+    unwrap: () => Promise<Returned>;
+};
+/**
+ * Config provided when calling the async thunk action creator.
+ */
+interface AsyncThunkDispatchConfig {
+    /**
+     * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
+     */
+    signal?: AbortSignal;
+}
+type AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, unknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [void] extends [ThunkArg] ? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [undefined] extends [ThunkArg] ? WithStrictNullChecks<(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> : (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;
+/**
+ * Options object for `createAsyncThunk`.
+ *
+ * @public
+ */
+type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {
+    /**
+     * A method to control whether the asyncThunk should be executed. Has access to the
+     * `arg`, `api.getState()` and `api.extra` arguments.
+     *
+     * @returns `false` if it should be skipped
+     */
+    condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;
+    /**
+     * If `condition` returns `false`, the asyncThunk will be skipped.
+     * This option allows you to control whether a `rejected` action with `meta.condition == false`
+     * will be dispatched or not.
+     *
+     * @default `false`
+     */
+    dispatchConditionRejection?: boolean;
+    serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;
+    /**
+     * A function to use when generating the `requestId` for the request sequence.
+     *
+     * @default `nanoid`
+     */
+    idGenerator?: (arg: ThunkArg) => string;
+} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     *
+     * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
+     * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
+     */
+    getPendingMeta?(base: {
+        arg: ThunkArg;
+        requestId: string;
+    }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
+}, {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     */
+    getPendingMeta(base: {
+        arg: ThunkArg;
+        requestId: string;
+    }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
+}>;
+type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
+    string,
+    ThunkArg,
+    GetPendingMeta<ThunkApiConfig>?
+], undefined, string, never, {
+    arg: ThunkArg;
+    requestId: string;
+    requestStatus: 'pending';
+} & GetPendingMeta<ThunkApiConfig>>;
+type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
+    Error | null,
+    string,
+    ThunkArg,
+    GetRejectValue<ThunkApiConfig>?,
+    GetRejectedMeta<ThunkApiConfig>?
+], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {
+    arg: ThunkArg;
+    requestId: string;
+    requestStatus: 'rejected';
+    aborted: boolean;
+    condition: boolean;
+} & (({
+    rejectedWithValue: false;
+} & {
+    [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined;
+}) | ({
+    rejectedWithValue: true;
+} & GetRejectedMeta<ThunkApiConfig>))>;
+type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
+    Returned,
+    string,
+    ThunkArg,
+    GetFulfilledMeta<ThunkApiConfig>?
+], Returned, string, never, {
+    arg: ThunkArg;
+    requestId: string;
+    requestStatus: 'fulfilled';
+} & GetFulfilledMeta<ThunkApiConfig>>;
+/**
+ * A type describing the return value of `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
+    pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;
+    rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;
+    fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;
+    settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;
+    typePrefix: string;
+};
+type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;
+type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {
+    /**
+     *
+     * @param typePrefix
+     * @param payloadCreator
+     * @param options
+     *
+     * @public
+     */
+    <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;
+    /**
+     *
+     * @param typePrefix
+     * @param payloadCreator
+     * @param options
+     *
+     * @public
+     */
+    <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
+};
+type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
+    withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
+};
+declare const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
+interface UnwrappableAction {
+    payload: any;
+    meta?: any;
+    error?: any;
+}
+type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {
+    error: any;
+}>['payload'];
+/**
+ * @public
+ */
+declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;
+type WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;
+
+type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {
+    pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;
+    rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;
+    fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;
+    settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;
+};
+type TypedActionCreator<Type extends string> = {
+    (...args: any[]): Action<Type>;
+    type: Type;
+};
+/**
+ * A builder for an action <-> reducer map.
+ *
+ * @public
+ */
+interface ActionReducerMapBuilder<State> {
+    /**
+     * Adds a case reducer to handle a single exact action type.
+     * @remarks
+     * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+     * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+     * @param reducer - The actual case reducer function.
+     */
+    addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;
+    /**
+     * Adds a case reducer to handle a single exact action type.
+     * @remarks
+     * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
+     * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+     * @param reducer - The actual case reducer function.
+     */
+    addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;
+    /**
+     * Adds case reducers to handle actions based on a `AsyncThunk` action creator.
+     * @remarks
+     * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+     * @param asyncThunk - The async thunk action creator itself.
+     * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
+     * @example
+  ```ts no-transpile
+  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'
+  
+  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
+    const response = await fetch(`https://reqres.in/api/users/${id}`)
+    return (await response.json()).data
+  })
+  
+  const reducer = createReducer(initialState, (builder) => {
+    builder.addAsyncThunk(fetchUserById, {
+      pending: (state, action) => {
+        state.fetchUserById.loading = 'pending'
+      },
+      fulfilled: (state, action) => {
+        state.fetchUserById.data = action.payload
+      },
+      rejected: (state, action) => {
+        state.fetchUserById.error = action.error
+      },
+      settled: (state, action) => {
+        state.fetchUserById.loading = action.meta.requestStatus
+      },
+    })
+  })
+     */
+    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;
+    /**
+     * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
+     * @remarks
+     * If multiple matcher reducers match, all of them will be executed in the order
+     * they were defined in - even if a case reducer already matched.
+     * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
+     * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
+     *   function
+     * @param reducer - The actual case reducer function.
+     *
+     * @example
+  ```ts
+  import {
+    createAction,
+    createReducer,
+    AsyncThunk,
+    UnknownAction,
+  } from "@reduxjs/toolkit";
+  
+  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
+  
+  type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
+  type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
+  type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
+  
+  const initialState: Record<string, string> = {};
+  const resetAction = createAction("reset-tracked-loading-state");
+  
+  function isPendingAction(action: UnknownAction): action is PendingAction {
+    return typeof action.type === "string" && action.type.endsWith("/pending");
+  }
+  
+  const reducer = createReducer(initialState, (builder) => {
+    builder
+      .addCase(resetAction, () => initialState)
+      // matcher can be defined outside as a type predicate function
+      .addMatcher(isPendingAction, (state, action) => {
+        state[action.meta.requestId] = "pending";
+      })
+      .addMatcher(
+        // matcher can be defined inline as a type predicate function
+        (action): action is RejectedAction => action.type.endsWith("/rejected"),
+        (state, action) => {
+          state[action.meta.requestId] = "rejected";
+        }
+      )
+      // matcher can just return boolean and the matcher can receive a generic argument
+      .addMatcher<FulfilledAction>(
+        (action) => action.type.endsWith("/fulfilled"),
+        (state, action) => {
+          state[action.meta.requestId] = "fulfilled";
+        }
+      );
+  });
+  ```
+     */
+    addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;
+    /**
+     * Adds a "default case" reducer that is executed if no case reducer and no matcher
+     * reducer was executed for this action.
+     * @param reducer - The fallback "default case" reducer function.
+     *
+     * @example
+  ```ts
+  import { createReducer } from '@reduxjs/toolkit'
+  const initialState = { otherActions: 0 }
+  const reducer = createReducer(initialState, builder => {
+    builder
+      // .addCase(...)
+      // .addMatcher(...)
+      .addDefaultCase((state, action) => {
+        state.otherActions++
+      })
+  })
+  ```
+     */
+    addDefaultCase(reducer: CaseReducer<State, Action>): {};
+}
+
+/**
+ * Defines a mapping from action types to corresponding action object shapes.
+ *
+ * @deprecated This should not be used manually - it is only used for internal
+ *             inference purposes and should not have any further value.
+ *             It might be removed in the future.
+ * @public
+ */
+type Actions<T extends keyof any = string> = Record<T, Action>;
+/**
+ * A *case reducer* is a reducer function for a specific action type. Case
+ * reducers can be composed to full reducers using `createReducer()`.
+ *
+ * Unlike a normal Redux reducer, a case reducer is never called with an
+ * `undefined` state to determine the initial state. Instead, the initial
+ * state is explicitly specified as an argument to `createReducer()`.
+ *
+ * In addition, a case reducer can choose to mutate the passed-in `state`
+ * value directly instead of returning a new state. This does not actually
+ * cause the store state to be mutated directly; instead, thanks to
+ * [immer](https://github.com/mweststrate/immer), the mutations are
+ * translated to copy operations that result in a new state.
+ *
+ * @public
+ */
+type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
+/**
+ * A mapping from action types to case reducers for `createReducer()`.
+ *
+ * @deprecated This should not be used manually - it is only used
+ *             for internal inference purposes and using it manually
+ *             would lead to type erasure.
+ *             It might be removed in the future.
+ * @public
+ */
+type CaseReducers<S, AS extends Actions> = {
+    [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;
+};
+type NotFunction<T> = T extends Function ? never : T;
+type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
+    getInitialState: () => S;
+};
+/**
+ * A utility function that allows defining a reducer as a mapping from action
+ * type to *case reducer* functions that handle these action types. The
+ * reducer's initial state is passed as the first argument.
+ *
+ * @remarks
+ * The body of every case reducer is implicitly wrapped with a call to
+ * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
+ * This means that rather than returning a new state object, you can also
+ * mutate the passed-in state object directly; these mutations will then be
+ * automatically and efficiently translated into copies, giving you both
+ * convenience and immutability.
+ *
+ * @overloadSummary
+ * This function accepts a callback that receives a `builder` object as its argument.
+ * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
+ * called to define what actions this reducer will handle.
+ *
+ * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+ * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
+ *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+ * @example
+```ts
+import {
+  createAction,
+  createReducer,
+  UnknownAction,
+  PayloadAction,
+} from "@reduxjs/toolkit";
+
+const increment = createAction<number>("increment");
+const decrement = createAction<number>("decrement");
+
+function isActionWithNumberPayload(
+  action: UnknownAction
+): action is PayloadAction<number> {
+  return typeof action.payload === "number";
+}
+
+const reducer = createReducer(
+  {
+    counter: 0,
+    sumOfNumberPayloads: 0,
+    unhandledActions: 0,
+  },
+  (builder) => {
+    builder
+      .addCase(increment, (state, action) => {
+        // action is inferred correctly here
+        state.counter += action.payload;
+      })
+      // You can chain calls, or have separate `builder.addCase()` lines each time
+      .addCase(decrement, (state, action) => {
+        state.counter -= action.payload;
+      })
+      // You can apply a "matcher function" to incoming actions
+      .addMatcher(isActionWithNumberPayload, (state, action) => {})
+      // and provide a default case if no other handlers matched
+      .addDefaultCase((state, action) => {});
+  }
+);
+```
+ * @public
+ */
+declare function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>;
+
+type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
+    reducerPath: ReducerPath;
+    reducer: Reducer<State, any, PreloadedState>;
+};
+type AnySliceLike = SliceLike<string, any>;
+type SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;
+type SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;
+type SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;
+type WithSlice<A extends AnySliceLike> = {
+    [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>;
+};
+type WithSlicePreloadedState<A extends AnySliceLike> = {
+    [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>;
+};
+type ReducerMap = Record<string, Reducer>;
+type ExistingSliceLike<DeclaredState, PreloadedState> = {
+    [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>>;
+}[keyof DeclaredState];
+type InjectConfig = {
+    /**
+     * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
+     */
+    overrideExisting?: boolean;
+};
+/**
+ * A reducer that allows for slices/reducers to be injected after initialisation.
+ */
+interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
+    /**
+     * Provide a type for slices that will be injected lazily.
+     *
+     * One way to do this would be with interface merging:
+     * ```ts
+     *
+     * export interface LazyLoadedSlices {}
+     *
+     * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+     *
+     * // elsewhere
+     *
+     * declare module './reducer' {
+     *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+     * }
+     *
+     * const withBoolean = rootReducer.inject(booleanSlice);
+     *
+     * // elsewhere again
+     *
+     * declare module './reducer' {
+     *   export interface LazyLoadedSlices {
+     *     customName: CustomState
+     *   }
+     * }
+     *
+     * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
+     * ```
+     */
+    withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;
+    /**
+     * Inject a slice.
+     *
+     * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+     *
+     * ```ts
+     * rootReducer.inject(booleanSlice)
+     * rootReducer.inject(baseApi)
+     * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+     * ```
+     *
+     */
+    inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;
+    /**
+     * Inject a slice.
+     *
+     * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+     *
+     * ```ts
+     * rootReducer.inject(booleanSlice)
+     * rootReducer.inject(baseApi)
+     * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+     * ```
+     *
+     */
+    inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;
+    /**
+     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+     *
+     * ```ts
+     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+     * //                                                                ^? boolean | undefined
+     *
+     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+     *   return state.boolean;
+     *   //           ^? boolean
+     * })
+     * ```
+     *
+     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+     *
+     * ```ts
+     *
+     * export interface LazyLoadedSlices {};
+     *
+     * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+     *
+     * export const rootReducer = combineSlices({ inner: innerReducer });
+     *
+     * export type RootState = ReturnType<typeof rootReducer>;
+     *
+     * // elsewhere
+     *
+     * declare module "./reducer.ts" {
+     *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+     * }
+     *
+     * const withBool = innerReducer.inject(booleanSlice);
+     *
+     * const selectBoolean = withBool.selector(
+     *   (state) => state.boolean,
+     *   (rootState: RootState) => state.inner
+     * );
+     * //    now expects to be passed RootState instead of innerReducer state
+     *
+     * ```
+     *
+     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+     *
+     * ```ts
+     * const injectedReducer = rootReducer.inject(booleanSlice);
+     * const selectBoolean = injectedReducer.selector((state) => {
+     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+     *   return state.boolean
+     * })
+     * ```
+     */
+    selector: {
+        /**
+         * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+         *
+         * ```ts
+         * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+         * //                                                                ^? boolean | undefined
+         *
+         * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+         *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+         *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+         *   return state.boolean;
+         *   //           ^? boolean
+         * })
+         * ```
+         *
+         * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+         *
+         * ```ts
+         * const injectedReducer = rootReducer.inject(booleanSlice);
+         * const selectBoolean = injectedReducer.selector((state) => {
+         *   console.log(injectedReducer.selector.original(state).boolean) // undefined
+         *   return state.boolean
+         * })
+         * ```
+         */
+        <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
+        /**
+         * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+         *
+         * ```ts
+         * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+         * //                                                                ^? boolean | undefined
+         *
+         * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+         *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+         *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+         *   return state.boolean;
+         *   //           ^? boolean
+         * })
+         * ```
+         *
+         * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+         *
+         * ```ts
+         *
+         * interface LazyLoadedSlices {};
+         *
+         * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+         *
+         * const rootReducer = combineSlices({ inner: innerReducer });
+         *
+         * type RootState = ReturnType<typeof rootReducer>;
+         *
+         * // elsewhere
+         *
+         * declare module "./reducer.ts" {
+         *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+         * }
+         *
+         * const withBool = innerReducer.inject(booleanSlice);
+         *
+         * const selectBoolean = withBool.selector(
+         *   (state) => state.boolean,
+         *   (rootState: RootState) => state.inner
+         * );
+         * //    now expects to be passed RootState instead of innerReducer state
+         *
+         * ```
+         *
+         * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+         *
+         * ```ts
+         * const injectedReducer = rootReducer.inject(booleanSlice);
+         * const selectBoolean = injectedReducer.selector((state) => {
+         *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+         *   return state.boolean
+         * })
+         * ```
+         */
+        <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
+        /**
+         * Returns the unproxied state. Useful for debugging.
+         * @param state state Proxy, that ensures injected reducers have value
+         * @returns original, unproxied state
+         * @throws if value passed is not a state Proxy
+         */
+        original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;
+    };
+}
+type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;
+type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;
+declare function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>>;
+
+declare const asyncThunkSymbol: unique symbol;
+declare const asyncThunkCreator: {
+    [asyncThunkSymbol]: typeof createAsyncThunk;
+};
+type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
+    reducerPath?: NewReducerPath;
+};
+/**
+ * The return value of `createSlice`
+ *
+ * @public
+ */
+interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
+    /**
+     * The slice name.
+     */
+    name: Name;
+    /**
+     *  The slice reducer path.
+     */
+    reducerPath: ReducerPath;
+    /**
+     * The slice's reducer.
+     */
+    reducer: Reducer<State>;
+    /**
+     * Action creators for the types of actions that are handled by the slice
+     * reducer.
+     */
+    actions: CaseReducerActions<CaseReducers, Name>;
+    /**
+     * The individual case reducer functions that were passed in the `reducers` parameter.
+     * This enables reuse and testing if they were defined inline when calling `createSlice`.
+     */
+    caseReducers: SliceDefinedCaseReducers<CaseReducers>;
+    /**
+     * Provides access to the initial state value given to the slice.
+     * If a lazy state initializer was provided, it will be called and a fresh value returned.
+     */
+    getInitialState: () => State;
+    /**
+     * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+     */
+    getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;
+    /**
+     * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+     */
+    getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
+    /**
+     * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
+     *
+     * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
+     */
+    get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
+        [K in ReducerPath]: State;
+    }>>;
+    /**
+     * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
+     */
+    injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {
+        inject: (slice: {
+            reducerPath: string;
+            reducer: Reducer;
+        }, config?: InjectConfig) => void;
+    }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;
+    /**
+     * Select the slice state, using the slice's current reducerPath.
+     *
+     * Will throw an error if slice is not found.
+     */
+    selectSlice(state: {
+        [K in ReducerPath]: State;
+    }): State;
+}
+/**
+ * A slice after being called with `injectInto(reducer)`.
+ *
+ * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
+ */
+type InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {
+    /**
+     * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+     */
+    getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;
+    /**
+     * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+     */
+    getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
+    /**
+     * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
+     *
+     * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
+     */
+    get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
+        [K in ReducerPath]?: State | undefined;
+    }>>;
+    /**
+     * Select the slice state, using the slice's current reducerPath.
+     *
+     * Returns initial state if slice is not found.
+     */
+    selectSlice(state: {
+        [K in ReducerPath]?: State | undefined;
+    }): State;
+};
+/**
+ * Options for `createSlice()`.
+ *
+ * @public
+ */
+interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
+    /**
+     * The slice's name. Used to namespace the generated action types.
+     */
+    name: Name;
+    /**
+     * The slice's reducer path. Used when injecting into a combined slice reducer.
+     */
+    reducerPath?: ReducerPath;
+    /**
+     * The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+     */
+    initialState: State | (() => State);
+    /**
+     * A mapping from action types to action-type-specific *case reducer*
+     * functions. For every action type, a matching action creator will be
+     * generated using `createAction()`.
+     */
+    reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);
+    /**
+     * A callback that receives a *builder* object to define
+     * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+     *
+     *
+     * @example
+  ```ts
+  import { createAction, createSlice, Action } from '@reduxjs/toolkit'
+  const incrementBy = createAction<number>('incrementBy')
+  const decrement = createAction('decrement')
+  
+  interface RejectedAction extends Action {
+    error: Error
+  }
+  
+  function isRejectedAction(action: Action): action is RejectedAction {
+    return action.type.endsWith('rejected')
+  }
+  
+  createSlice({
+    name: 'counter',
+    initialState: 0,
+    reducers: {},
+    extraReducers: builder => {
+      builder
+        .addCase(incrementBy, (state, action) => {
+          // action is inferred correctly here if using TS
+        })
+        // You can chain calls, or have separate `builder.addCase()` lines each time
+        .addCase(decrement, (state, action) => {})
+        // You can match a range of action types
+        .addMatcher(
+          isRejectedAction,
+          // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
+          (state, action) => {}
+        )
+        // and provide a default case if no other handlers matched
+        .addDefaultCase((state, action) => {})
+      }
+  })
+  ```
+     */
+    extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;
+    /**
+     * A map of selectors that receive the slice's state and any additional arguments, and return a result.
+     */
+    selectors?: Selectors;
+}
+declare enum ReducerType {
+    reducer = "reducer",
+    reducerWithPrepare = "reducerWithPrepare",
+    asyncThunk = "asyncThunk"
+}
+type ReducerDefinition<T extends ReducerType = ReducerType> = {
+    _reducerDefinitionType: T;
+};
+type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;
+/**
+ * A CaseReducer with a `prepare` method.
+ *
+ * @public
+ */
+type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
+    reducer: CaseReducer<State, Action>;
+    prepare: PrepareAction<Action['payload']>;
+};
+type AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
+    options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;
+};
+type AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {
+    payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;
+};
+/**
+ * Providing these as part of the config would cause circular types, so we disallow passing them
+ */
+type PreventCircular<ThunkApiConfig> = {
+    [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K];
+};
+interface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {
+    <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;
+    <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;
+    withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
+}
+interface ReducerCreators<State> {
+    reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;
+    reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;
+    asyncThunk: AsyncThunkCreator<State>;
+    preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {
+        _reducerDefinitionType: ReducerType.reducerWithPrepare;
+        prepare: Prepare;
+        reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;
+    };
+}
+/**
+ * The type describing a slice's `reducers` option.
+ *
+ * @public
+ */
+type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;
+/**
+ * The type describing a slice's `selectors` option.
+ */
+type SliceSelectors<State> = {
+    [K: string]: (sliceState: State, ...args: any[]) => any;
+};
+type SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;
+/**
+ * Derives the slice's `actions` property from the `reducers` options
+ *
+ * @public
+ */
+type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = {
+    [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {
+        prepare: any;
+    } ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {
+        reducer: any;
+    } ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never;
+};
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducerWithPrepare<CR extends {
+    prepare: any;
+}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducer`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (state: any, action: infer Action) => any ? Action extends {
+    payload: infer P;
+} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;
+/**
+ * Extracts the CaseReducers out of a `reducers` object, even if they are
+ * tested into a `CaseReducerWithPrepare`.
+ *
+ * @internal
+ */
+type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
+    [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {
+        reducer: infer Reducer;
+    } ? Reducer : Definition : never;
+};
+type RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {
+    unwrapped: S;
+} : never;
+/**
+ * Extracts the final selector type from the `selectors` object.
+ *
+ * Removes the `string` index signature from the default value.
+ */
+type SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = {
+    [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState>;
+};
+/**
+ * Used on a SliceCaseReducers object.
+ * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
+ * the `reducer` and the `prepare` function use the same type of `payload`.
+ *
+ * Might do additional such checks in the future.
+ *
+ * This type is only ever useful if you want to write your own wrapper around
+ * `createSlice`. Please don't use it otherwise!
+ *
+ * @public
+ */
+type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
+    [T in keyof ACR]: ACR[T] extends {
+        reducer(s: S, action?: infer A): any;
+    } ? {
+        prepare(...a: never[]): Omit<A, 'type'>;
+    } : {};
+};
+interface BuildCreateSliceConfig {
+    creators?: {
+        asyncThunk?: typeof asyncThunkCreator;
+    };
+}
+declare function buildCreateSlice({ creators }?: BuildCreateSliceConfig): <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
+/**
+ * A function that accepts an initial state, an object full of reducer
+ * functions, and a "slice name", and automatically generates
+ * action creators and action types that correspond to the
+ * reducers and state.
+ *
+ * @public
+ */
+declare const createSlice: <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
+
+type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;
+type GetSelectorsOptions = {
+    createSelector?: AnyCreateSelectorFunction;
+};
+
+/**
+ * @public
+ */
+type EntityId = number | string;
+/**
+ * @public
+ */
+type Comparer<T> = (a: T, b: T) => number;
+/**
+ * @public
+ */
+type IdSelector<T, Id extends EntityId> = (model: T) => Id;
+/**
+ * @public
+ */
+type Update<T, Id extends EntityId> = {
+    id: Id;
+    changes: Partial<T>;
+};
+/**
+ * @public
+ */
+interface EntityState<T, Id extends EntityId> {
+    ids: Id[];
+    entities: Record<Id, T>;
+}
+/**
+ * @public
+ */
+interface EntityAdapterOptions<T, Id extends EntityId> {
+    selectId?: IdSelector<T, Id>;
+    sortComparer?: false | Comparer<T>;
+}
+type PreventAny<S, T, Id extends EntityId> = CastAny<S, EntityState<T, Id>>;
+type DraftableEntityState<T, Id extends EntityId> = EntityState<T, Id> | Draft<EntityState<T, Id>>;
+/**
+ * @public
+ */
+interface EntityStateAdapter<T, Id extends EntityId> {
+    addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
+    addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
+    addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+    setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
+    setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
+    setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+    setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+    removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: Id): S;
+    removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: PayloadAction<Id>): S;
+    removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: readonly Id[]): S;
+    removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: PayloadAction<readonly Id[]>): S;
+    removeAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S;
+    updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: Update<T, Id>): S;
+    updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: PayloadAction<Update<T, Id>>): S;
+    updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: ReadonlyArray<Update<T, Id>>): S;
+    updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: PayloadAction<ReadonlyArray<Update<T, Id>>>): S;
+    upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
+    upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: PayloadAction<T>): S;
+    upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
+    upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
+}
+/**
+ * @public
+ */
+interface EntitySelectors<T, V, IdType extends EntityId> {
+    selectIds: (state: V) => IdType[];
+    selectEntities: (state: V) => Record<IdType, T>;
+    selectAll: (state: V) => T[];
+    selectTotal: (state: V) => number;
+    selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>;
+}
+/**
+ * @public
+ */
+interface EntityStateFactory<T, Id extends EntityId> {
+    getInitialState(state?: undefined, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id>;
+    getInitialState<S extends object>(state: S, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id> & S;
+}
+/**
+ * @public
+ */
+interface EntityAdapter<T, Id extends EntityId> extends EntityStateAdapter<T, Id>, EntityStateFactory<T, Id>, Required<EntityAdapterOptions<T, Id>> {
+    getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;
+    getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;
+}
+
+declare function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;
+declare function createEntityAdapter<T extends {
+    id: EntityId;
+}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;
+
+/** @public */
+type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;
+/** @public */
+type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches any one of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+declare function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAnyOf<Matchers>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches all of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+declare function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAllOf<Matchers>;
+type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;
+type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is pending.
+ *
+ * @public
+ */
+declare function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is pending.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a pending thunk action
+ * @public
+ */
+declare function isPending(action: any): action is UnknownAsyncThunkPendingAction;
+type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
+type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected.
+ *
+ * @public
+ */
+declare function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a rejected thunk action
+ * @public
+ */
+declare function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;
+type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {
+    rejectValue: infer RejectedValue;
+}> ? {
+    payload: RejectedValue;
+} : unknown);
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected with value.
+ *
+ * @public
+ */
+declare function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected with value.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a rejected thunk action with value
+ * @public
+ */
+declare function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;
+type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;
+type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is fulfilled.
+ *
+ * @public
+ */
+declare function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is fulfilled.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a fulfilled thunk action
+ * @public
+ */
+declare function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;
+type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;
+type AnyAsyncThunk = {
+    pending: {
+        match: (action: any) => action is any;
+    };
+    fulfilled: {
+        match: (action: any) => action is any;
+    };
+    rejected: {
+        match: (action: any) => action is any;
+    };
+};
+type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator.
+ *
+ * @public
+ */
+declare function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+declare function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;
+/**
+ * Tests if `action` is a thunk action
+ * @public
+ */
+declare function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;
+
+/**
+ *
+ * @public
+ */
+declare let nanoid: (size?: number) => string;
+
+declare class TaskAbortError implements SerializedError {
+    code: string | undefined;
+    name: string;
+    message: string;
+    constructor(code: string | undefined);
+}
+
+/**
+ * Types copied from RTK
+ */
+/** @internal */
+type TypedActionCreatorWithMatchFunction<Type extends string> = TypedActionCreator<Type> & {
+    match: MatchFunction<any>;
+};
+/** @internal */
+type AnyListenerPredicate<State> = (action: UnknownAction, currentState: State, originalState: State) => boolean;
+/** @public */
+type ListenerPredicate<ActionType extends Action, State> = (action: UnknownAction, currentState: State, originalState: State) => action is ActionType;
+/** @public */
+interface ConditionFunction<State> {
+    (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
+    (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
+    (predicate: () => boolean, timeout?: number): Promise<boolean>;
+}
+/** @internal */
+type MatchFunction<T> = (v: any) => v is T;
+/** @public */
+interface ForkedTaskAPI {
+    /**
+     * Returns a promise that resolves when `waitFor` resolves or
+     * rejects if the task or the parent listener has been cancelled or is completed.
+     */
+    pause<W>(waitFor: Promise<W>): Promise<W>;
+    /**
+     * Returns a promise that resolves after `timeoutMs` or
+     * rejects if the task or the parent listener has been cancelled or is completed.
+     * @param timeoutMs
+     */
+    delay(timeoutMs: number): Promise<void>;
+    /**
+     * An abort signal whose `aborted` property is set to `true`
+     * if the task execution is either aborted or completed.
+     * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+     */
+    signal: AbortSignal;
+}
+/** @public */
+interface AsyncTaskExecutor<T> {
+    (forkApi: ForkedTaskAPI): Promise<T>;
+}
+/** @public */
+interface SyncTaskExecutor<T> {
+    (forkApi: ForkedTaskAPI): T;
+}
+/** @public */
+type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
+/** @public */
+type TaskResolved<T> = {
+    readonly status: 'ok';
+    readonly value: T;
+};
+/** @public */
+type TaskRejected = {
+    readonly status: 'rejected';
+    readonly error: unknown;
+};
+/** @public */
+type TaskCancelled = {
+    readonly status: 'cancelled';
+    readonly error: TaskAbortError;
+};
+/** @public */
+type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
+/** @public */
+interface ForkedTask<T> {
+    /**
+     * A promise that resolves when the task is either completed or cancelled or rejects
+     * if parent listener execution is cancelled or completed.
+     *
+     * ### Example
+     * ```ts
+     * const result = await fork(async (forkApi) => Promise.resolve(4)).result
+     *
+     * if(result.status === 'ok') {
+     *   console.log(result.value) // logs 4
+     * }}
+     * ```
+     */
+    result: Promise<TaskResult<T>>;
+    /**
+     * Cancel task if it is in progress or not yet started,
+     * it is noop otherwise.
+     */
+    cancel(): void;
+}
+/** @public */
+interface ForkOptions {
+    /**
+     * If true, causes the parent task to not be marked as complete until
+     * all autoJoined forks have completed or failed.
+     */
+    autoJoin: boolean;
+}
+/** @public */
+interface ListenerEffectAPI<State, DispatchType extends Dispatch, ExtraArgument = unknown> extends MiddlewareAPI<DispatchType, State> {
+    /**
+     * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
+     *
+     * ### Synchronous invocation
+     *
+     * This function can **only** be invoked **synchronously**, it throws error otherwise.
+     *
+     * @example
+     *
+     * ```ts
+     * middleware.startListening({
+     *  predicate: () => true,
+     *  async effect(_, { getOriginalState }) {
+     *    getOriginalState(); // sync: OK!
+     *
+     *    setTimeout(getOriginalState, 0); // async: throws Error
+     *
+     *    await Promise().resolve();
+     *
+     *    getOriginalState() // async: throws Error
+     *  }
+     * })
+     * ```
+     */
+    getOriginalState: () => State;
+    /**
+     * Removes the listener entry from the middleware and prevent future instances of the listener from running.
+     *
+     * It does **not** cancel any active instances.
+     */
+    unsubscribe(): void;
+    /**
+     * It will subscribe a listener if it was previously removed, noop otherwise.
+     */
+    subscribe(): void;
+    /**
+     * Returns a promise that resolves when the input predicate returns `true` or
+     * rejects if the listener has been cancelled or is completed.
+     *
+     * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
+     *
+     * ### Example
+     *
+     * ```ts
+     * const updateBy = createAction<number>('counter/updateBy');
+     *
+     * middleware.startListening({
+     *  actionCreator: updateBy,
+     *  async effect(_, { condition }) {
+     *    // wait at most 3s for `updateBy` actions.
+     *    if(await condition(updateBy.match, 3_000)) {
+     *      // `updateBy` has been dispatched twice in less than 3s.
+     *    }
+     *  }
+     * })
+     * ```
+     */
+    condition: ConditionFunction<State>;
+    /**
+     * Returns a promise that resolves when the input predicate returns `true` or
+     * rejects if the listener has been cancelled or is completed.
+     *
+     * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
+     *
+     * The promise resolves to null if a timeout is provided and expires first,
+     *
+     * ### Example
+     *
+     * ```ts
+     * const updateBy = createAction<number>('counter/updateBy');
+     *
+     * middleware.startListening({
+     *  actionCreator: updateBy,
+     *  async effect(_, { take }) {
+     *    const [{ payload }] =  await take(updateBy.match);
+     *    console.log(payload); // logs 5;
+     *  }
+     * })
+     *
+     * store.dispatch(updateBy(5));
+     * ```
+     */
+    take: TakePattern<State>;
+    /**
+     * Cancels all other running instances of this same listener except for the one that made this call.
+     */
+    cancelActiveListeners: () => void;
+    /**
+     * Cancels the instance of this listener that made this call.
+     */
+    cancel: () => void;
+    /**
+     * Throws a `TaskAbortError` if this listener has been cancelled
+     */
+    throwIfCancelled: () => void;
+    /**
+     * An abort signal whose `aborted` property is set to `true`
+     * if the listener execution is either aborted or completed.
+     * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+     */
+    signal: AbortSignal;
+    /**
+     * Returns a promise that resolves after `timeoutMs` or
+     * rejects if the listener has been cancelled or is completed.
+     */
+    delay(timeoutMs: number): Promise<void>;
+    /**
+     * Queues in the next microtask the execution of a task.
+     * @param executor
+     * @param options
+     */
+    fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>;
+    /**
+     * Returns a promise that resolves when `waitFor` resolves or
+     * rejects if the listener has been cancelled or is completed.
+     * @param promise
+     */
+    pause<M>(promise: Promise<M>): Promise<M>;
+    extra: ExtraArgument;
+}
+/** @public */
+type ListenerEffect<ActionType extends Action, State, DispatchType extends Dispatch, ExtraArgument = unknown> = (action: ActionType, api: ListenerEffectAPI<State, DispatchType, ExtraArgument>) => void | Promise<void>;
+/**
+ * @public
+ * Additional infos regarding the error raised.
+ */
+interface ListenerErrorInfo {
+    /**
+     * Which function has generated the exception.
+     */
+    raisedBy: 'effect' | 'predicate';
+}
+/**
+ * @public
+ * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
+ * @param error The thrown error.
+ * @param errorInfo Additional information regarding the thrown error.
+ */
+interface ListenerErrorHandler {
+    (error: unknown, errorInfo: ListenerErrorInfo): void;
+}
+/** @public */
+interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
+    extra?: ExtraArgument;
+    /**
+     * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
+     */
+    onError?: ListenerErrorHandler;
+}
+/** @public */
+type ListenerMiddleware<State = unknown, DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<State, unknown, UnknownAction>, ExtraArgument = unknown> = Middleware<{
+    (action: Action<'listenerMiddleware/add'>): UnsubscribeListener;
+}, State, DispatchType>;
+/** @public */
+interface ListenerMiddlewareInstance<StateType = unknown, DispatchType extends ThunkDispatch<StateType, unknown, Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> {
+    middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>;
+    startListening: AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & TypedStartListening<StateType, DispatchType, ExtraArgument>;
+    stopListening: RemoveListenerOverloads<StateType, DispatchType> & TypedStopListening<StateType, DispatchType>;
+    /**
+     * Unsubscribes all listeners, cancels running listeners and tasks.
+     */
+    clearListeners: () => void;
+}
+/**
+ * API Function Overloads
+ */
+/** @public */
+type TakePatternOutputWithoutTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State]> : Promise<[UnknownAction, State, State]>;
+/** @public */
+type TakePatternOutputWithTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State] | null> : Promise<[UnknownAction, State, State] | null>;
+/** @public */
+interface TakePattern<State> {
+    <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate): TakePatternOutputWithoutTimeout<State, Predicate>;
+    <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout: number): TakePatternOutputWithTimeout<State, Predicate>;
+    <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout?: number | undefined): TakePatternOutputWithTimeout<State, Predicate>;
+}
+/** @public */
+interface UnsubscribeListenerOptions {
+    cancelActive?: true;
+}
+/** @public */
+type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
+/**
+ * @public
+ * The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
+ */
+type AddListenerOverloads<Return, StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, AdditionalOptions = unknown> = {
+    /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
+    <MiddlewareActionType extends UnknownAction, ListenerPredicateType extends ListenerPredicate<MiddlewareActionType, StateType>>(options: {
+        actionCreator?: never;
+        type?: never;
+        matcher?: never;
+        predicate: ListenerPredicateType;
+        effect: ListenerEffect<ListenerPredicateGuardedActionType<ListenerPredicateType>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts an RTK action creator, like `incrementByAmount` */
+    <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(options: {
+        actionCreator: ActionCreatorType;
+        type?: never;
+        matcher?: never;
+        predicate?: never;
+        effect: ListenerEffect<ReturnType<ActionCreatorType>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts a specific action type string */
+    <T extends string>(options: {
+        actionCreator?: never;
+        type: T;
+        matcher?: never;
+        predicate?: never;
+        effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
+    <MatchFunctionType extends MatchFunction<UnknownAction>>(options: {
+        actionCreator?: never;
+        type?: never;
+        matcher: MatchFunctionType;
+        predicate?: never;
+        effect: ListenerEffect<GuardedType<MatchFunctionType>, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+    /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
+    <ListenerPredicateType extends AnyListenerPredicate<StateType>>(options: {
+        actionCreator?: never;
+        type?: never;
+        matcher?: never;
+        predicate: ListenerPredicateType;
+        effect: ListenerEffect<UnknownAction, StateType, DispatchType, ExtraArgument>;
+    } & AdditionalOptions): Return;
+};
+/** @public */
+type RemoveListenerOverloads<StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<boolean, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions>;
+/**
+ * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedAddListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/add'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument> & {
+    /**
+     * Creates a "pre-typed" version of `addListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `addListener` call.
+     *
+     * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { addListener } from '@reduxjs/toolkit'
+     *
+     * export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedAddListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedRemoveListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/remove'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions> & {
+    /**
+     * Creates a "pre-typed" version of `removeListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `removeListener` call.
+     *
+     * @returns A pre-typed `removeListener` with the state, dispatch and extra
+     * types already defined.
+     *
+     * @example
+     * ```ts
+     * import { removeListener } from '@reduxjs/toolkit'
+     *
+     * export const removeAppListener = removeListener.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedRemoveListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedStartListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & {
+    /**
+     * Creates a "pre-typed" version of
+     * {@linkcode ListenerMiddlewareInstance.startListening startListening}
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every
+     * {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
+     *
+     * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { createListenerMiddleware } from '@reduxjs/toolkit'
+     *
+     * const listenerMiddleware = createListenerMiddleware()
+     *
+     * export const startAppListening = listenerMiddleware.startListening.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStartListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+type TypedStopListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
+    /**
+     * Creates a "pre-typed" version of
+     * {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every
+     * {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
+     *
+     * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { createListenerMiddleware } from '@reduxjs/toolkit'
+     *
+     * const listenerMiddleware = createListenerMiddleware()
+     *
+     * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
+};
+/**
+ * Internal Types
+ */
+/** @internal An single listener entry */
+type ListenerEntry<State = unknown, DispatchType extends Dispatch = Dispatch> = {
+    id: string;
+    effect: ListenerEffect<any, State, DispatchType>;
+    unsubscribe: () => void;
+    pending: Set<AbortController>;
+    type?: string;
+    predicate: ListenerPredicate<UnknownAction, State>;
+};
+/**
+ * Utility Types
+ */
+/** @public */
+type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T ? T : never;
+/** @public */
+type ListenerPredicateGuardedActionType<T> = T extends ListenerPredicate<infer ActionType, any> ? ActionType : never;
+
+/**
+ * @public
+ */
+declare const addListener: TypedAddListener<unknown>;
+/**
+ * @public
+ */
+declare const clearAllListeners: ActionCreatorWithoutPayload<"listenerMiddleware/removeAll">;
+/**
+ * @public
+ */
+declare const removeListener: TypedRemoveListener<unknown>;
+/**
+ * @public
+ */
+declare const createListenerMiddleware: <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>) => ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;
+
+type MiddlewareApiConfig = {
+    state?: unknown;
+    dispatch?: Dispatch;
+};
+type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
+    dispatch: infer DispatchType;
+} ? FallbackIfUnknown<DispatchType, Dispatch> : Dispatch;
+type AddMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
+    (...middlewares: Middleware<any, State, DispatchType>[]): void;
+    withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
+};
+type WithMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = BaseActionCreator<Middleware<any, State, DispatchType>[], 'dynamicMiddleware/add', {
+    instanceId: string;
+}> & {
+    <Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares): PayloadAction<Middlewares, 'dynamicMiddleware/add', {
+        instanceId: string;
+    }>;
+    withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
+};
+interface DynamicDispatch {
+    <Middlewares extends Middleware<any>[]>(action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>): ExtractDispatchExtensions<Middlewares> & this;
+}
+type DynamicMiddleware<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = Middleware<DynamicDispatch, State, DispatchType>;
+type DynamicMiddlewareInstance<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
+    middleware: DynamicMiddleware<State, DispatchType>;
+    addMiddleware: AddMiddleware<State, DispatchType>;
+    withMiddleware: WithMiddleware<State, DispatchType>;
+    instanceId: string;
+};
+
+declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => DynamicMiddlewareInstance<State, DispatchType>;
+
+/**
+ * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
+ *
+ * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
+ * during build.
+ * @param {number} code
+ */
+declare function formatProdErrorMessage(code: number): string;
+
+export { type ActionCreatorInvariantMiddlewareOptions, type ActionCreatorWithNonInferrablePayload, type ActionCreatorWithOptionalPayload, type ActionCreatorWithPayload, type ActionCreatorWithPreparedPayload, type ActionCreatorWithoutPayload, type ActionMatchingAllOf, type ActionMatchingAnyOf, type ActionReducerMapBuilder, type Actions, type AddMiddleware, type AnyListenerPredicate, type AsyncTaskExecutor, type AsyncThunk, type AsyncThunkAction, type AsyncThunkConfig, type AsyncThunkDispatchConfig, type AsyncThunkOptions, type AsyncThunkPayloadCreator, type AsyncThunkPayloadCreatorReturnValue, type AsyncThunkReducers, type AutoBatchOptions, type CaseReducer, type CaseReducerActions, type CaseReducerWithPrepare, type CaseReducers, type CombinedSliceReducer, type Comparer, type ConfigureStoreOptions, type CreateAsyncThunkFunction, type CreateListenerMiddlewareOptions, type CreateSliceOptions, type DevToolsEnhancerOptions, type DynamicDispatch, type DynamicMiddlewareInstance, type EnhancedStore, type EntityAdapter, type EntityId, type EntitySelectors, type EntityState, type EntityStateAdapter, type ForkedTask, type ForkedTaskAPI, type ForkedTaskExecutor, type GetDispatchType as GetDispatch, type GetState, type GetThunkAPI, type IdSelector, type ImmutableStateInvariantMiddlewareOptions, type ListenerEffect, type ListenerEffectAPI, type ListenerErrorHandler, type ListenerMiddleware, type ListenerMiddlewareInstance, type MiddlewareApiConfig, type PayloadAction, type PayloadActionCreator, type PrepareAction, type ReducerCreators, ReducerType, SHOULD_AUTOBATCH, type SafePromise, type SerializableStateInvariantMiddlewareOptions, type SerializedError, type Slice, type SliceCaseReducers, type SliceSelectors, type SyncTaskExecutor, type ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, TaskAbortError, type TaskCancelled, type TaskRejected, type TaskResolved, type TaskResult, Tuple, type TypedAddListener, type TypedRemoveListener, type TypedStartListening, type TypedStopListening, type UnsubscribeListener, type UnsubscribeListenerOptions, type Update, type ValidateSliceCaseReducers, type WithSlice, type WithSlicePreloadedState, addListener, asyncThunkCreator, autoBatchEnhancer, buildCreateSlice, clearAllListeners, combineSlices, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, createReducer, createSerializableStateInvariantMiddleware, createSlice, findNonSerializableValue, formatProdErrorMessage, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isRejected, isRejectedWithValue, miniSerializeError, nanoid, prepareAutoBatched, removeListener, unwrapResult };
Index: node_modules/@reduxjs/toolkit/dist/query/cjs/index.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+'use strict'
+if (process.env.NODE_ENV === 'production') {
+  module.exports = require('./rtk-query.production.min.cjs')
+} else {
+  module.exports = require('./rtk-query.development.cjs')
+}
Index: node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.development.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3087 @@
+"use strict";
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// src/query/index.ts
+var query_exports = {};
+__export(query_exports, {
+  NamedSchemaError: () => NamedSchemaError,
+  QueryStatus: () => QueryStatus,
+  _NEVER: () => _NEVER,
+  buildCreateApi: () => buildCreateApi,
+  copyWithStructuralSharing: () => copyWithStructuralSharing,
+  coreModule: () => coreModule,
+  coreModuleName: () => coreModuleName,
+  createApi: () => createApi,
+  defaultSerializeQueryArgs: () => defaultSerializeQueryArgs,
+  fakeBaseQuery: () => fakeBaseQuery,
+  fetchBaseQuery: () => fetchBaseQuery,
+  retry: () => retry,
+  setupListeners: () => setupListeners,
+  skipToken: () => skipToken
+});
+module.exports = __toCommonJS(query_exports);
+
+// src/query/core/apiState.ts
+var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
+  QueryStatus7["uninitialized"] = "uninitialized";
+  QueryStatus7["pending"] = "pending";
+  QueryStatus7["fulfilled"] = "fulfilled";
+  QueryStatus7["rejected"] = "rejected";
+  return QueryStatus7;
+})(QueryStatus || {});
+var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
+var STATUS_PENDING = "pending" /* pending */;
+var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
+var STATUS_REJECTED = "rejected" /* rejected */;
+function getRequestStatusFlags(status) {
+  return {
+    status,
+    isUninitialized: status === STATUS_UNINITIALIZED,
+    isLoading: status === STATUS_PENDING,
+    isSuccess: status === STATUS_FULFILLED,
+    isError: status === STATUS_REJECTED
+  };
+}
+
+// src/query/core/rtkImports.ts
+var import_toolkit = require("@reduxjs/toolkit");
+
+// src/query/utils/copyWithStructuralSharing.ts
+var isPlainObject2 = import_toolkit.isPlainObject;
+function copyWithStructuralSharing(oldObj, newObj) {
+  if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
+    return newObj;
+  }
+  const newKeys = Object.keys(newObj);
+  const oldKeys = Object.keys(oldObj);
+  let isSameObject = newKeys.length === oldKeys.length;
+  const mergeObj = Array.isArray(newObj) ? [] : {};
+  for (const key of newKeys) {
+    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
+    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
+  }
+  return isSameObject ? oldObj : mergeObj;
+}
+
+// src/query/utils/filterMap.ts
+function filterMap(array, predicate, mapper) {
+  return array.reduce((acc, item, i) => {
+    if (predicate(item, i)) {
+      acc.push(mapper(item, i));
+    }
+    return acc;
+  }, []).flat();
+}
+
+// src/query/utils/isAbsoluteUrl.ts
+function isAbsoluteUrl(url) {
+  return new RegExp(`(^|:)//`).test(url);
+}
+
+// src/query/utils/isDocumentVisible.ts
+function isDocumentVisible() {
+  if (typeof document === "undefined") {
+    return true;
+  }
+  return document.visibilityState !== "hidden";
+}
+
+// src/query/utils/isNotNullish.ts
+function isNotNullish(v) {
+  return v != null;
+}
+function filterNullishValues(map) {
+  return [...map?.values() ?? []].filter(isNotNullish);
+}
+
+// src/query/utils/isOnline.ts
+function isOnline() {
+  return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
+}
+
+// src/query/utils/joinUrls.ts
+var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
+var withoutLeadingSlash = (url) => url.replace(/^\//, "");
+function joinUrls(base, url) {
+  if (!base) {
+    return url;
+  }
+  if (!url) {
+    return base;
+  }
+  if (isAbsoluteUrl(url)) {
+    return url;
+  }
+  const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
+  base = withoutTrailingSlash(base);
+  url = withoutLeadingSlash(url);
+  return `${base}${delimiter}${url}`;
+}
+
+// src/query/utils/getOrInsert.ts
+function getOrInsertComputed(map, key, compute) {
+  if (map.has(key)) return map.get(key);
+  return map.set(key, compute(key)).get(key);
+}
+var createNewMap = () => /* @__PURE__ */ new Map();
+
+// src/query/utils/signals.ts
+var timeoutSignal = (milliseconds) => {
+  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;
+};
+var anySignal = (...signals) => {
+  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
+  const abortController = new AbortController();
+  for (const signal of signals) {
+    signal.addEventListener("abort", () => abortController.abort(signal.reason), {
+      signal: abortController.signal,
+      once: true
+    });
+  }
+  return abortController.signal;
+};
+
+// src/query/fetchBaseQuery.ts
+var defaultFetchFn = (...args) => fetch(...args);
+var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
+var defaultIsJsonContentType = (headers) => (
+  /*applicat*/
+  /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
+);
+function stripUndefined(obj) {
+  if (!(0, import_toolkit.isPlainObject)(obj)) {
+    return obj;
+  }
+  const copy = {
+    ...obj
+  };
+  for (const [k, v] of Object.entries(copy)) {
+    if (v === void 0) delete copy[k];
+  }
+  return copy;
+}
+var isJsonifiable = (body) => typeof body === "object" && ((0, import_toolkit.isPlainObject)(body) || Array.isArray(body) || typeof body.toJSON === "function");
+function fetchBaseQuery({
+  baseUrl,
+  prepareHeaders = (x) => x,
+  fetchFn = defaultFetchFn,
+  paramsSerializer,
+  isJsonContentType = defaultIsJsonContentType,
+  jsonContentType = "application/json",
+  jsonReplacer,
+  timeout: defaultTimeout,
+  responseHandler: globalResponseHandler,
+  validateStatus: globalValidateStatus,
+  ...baseFetchOptions
+} = {}) {
+  if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
+    console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
+  }
+  return async (arg, api, extraOptions) => {
+    const {
+      getState,
+      extra,
+      endpoint,
+      forced,
+      type
+    } = api;
+    let meta;
+    let {
+      url,
+      headers = new Headers(baseFetchOptions.headers),
+      params = void 0,
+      responseHandler = globalResponseHandler ?? "json",
+      validateStatus = globalValidateStatus ?? defaultValidateStatus,
+      timeout = defaultTimeout,
+      ...rest
+    } = typeof arg == "string" ? {
+      url: arg
+    } : arg;
+    let config = {
+      ...baseFetchOptions,
+      signal: 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);
+    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);
+    }
+    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, */*");
+      }
+    }
+    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;
+    let responseText = "";
+    try {
+      let handleResponseError;
+      await Promise.all([
+        handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
+        // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
+        // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
+        responseClone.text().then((r) => responseText = r, () => {
+        })
+      ]);
+      if (handleResponseError) throw handleResponseError;
+    } catch (e) {
+      return {
+        error: {
+          status: "PARSING_ERROR",
+          originalStatus: response.status,
+          data: responseText,
+          error: String(e)
+        },
+        meta
+      };
+    }
+    return validateStatus(response, resultData) ? {
+      data: resultData,
+      meta
+    } : {
+      error: {
+        status: response.status,
+        data: resultData
+      },
+      meta
+    };
+  };
+  async function handleResponse(response, responseHandler) {
+    if (typeof responseHandler === "function") {
+      return responseHandler(response);
+    }
+    if (responseHandler === "content-type") {
+      responseHandler = isJsonContentType(response.headers) ? "json" : "text";
+    }
+    if (responseHandler === "json") {
+      const text = await response.text();
+      return text.length ? JSON.parse(text) : null;
+    }
+    return response.text();
+  }
+}
+
+// src/query/HandledError.ts
+var HandledError = class {
+  constructor(value, meta = void 0) {
+    this.value = value;
+    this.meta = meta;
+  }
+};
+
+// src/query/retry.ts
+async function defaultBackoff(attempt = 0, maxRetries = 5, signal) {
+  const attempts = Math.min(attempt, maxRetries);
+  const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
+  await new Promise((resolve, reject) => {
+    const timeoutId = setTimeout(() => resolve(), timeout);
+    if (signal) {
+      const abortHandler = () => {
+        clearTimeout(timeoutId);
+        reject(new Error("Aborted"));
+      };
+      if (signal.aborted) {
+        clearTimeout(timeoutId);
+        reject(new Error("Aborted"));
+      } else {
+        signal.addEventListener("abort", abortHandler, {
+          once: true
+        });
+      }
+    }
+  });
+}
+function fail(error, meta) {
+  throw Object.assign(new HandledError({
+    error,
+    meta
+  }), {
+    throwImmediately: true
+  });
+}
+function failIfAborted(signal) {
+  if (signal.aborted) {
+    fail({
+      status: "CUSTOM_ERROR",
+      error: "Aborted"
+    });
+  }
+}
+var EMPTY_OPTIONS = {};
+var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
+  const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
+  const [maxRetries] = possibleMaxRetries.slice(-1);
+  const defaultRetryCondition = (_, __, {
+    attempt
+  }) => attempt <= maxRetries;
+  const options = {
+    maxRetries,
+    backoff: defaultBackoff,
+    retryCondition: defaultRetryCondition,
+    ...defaultOptions,
+    ...extraOptions
+  };
+  let retry2 = 0;
+  while (true) {
+    failIfAborted(api.signal);
+    try {
+      const result = await baseQuery(args, api, extraOptions);
+      if (result.error) {
+        throw new HandledError(result);
+      }
+      return result;
+    } catch (e) {
+      retry2++;
+      if (e.throwImmediately) {
+        if (e instanceof HandledError) {
+          return e.value;
+        }
+        throw e;
+      }
+      if (e instanceof HandledError) {
+        if (!options.retryCondition(e.value.error, args, {
+          attempt: retry2,
+          baseQueryApi: api,
+          extraOptions
+        })) {
+          return e.value;
+        }
+      } else {
+        if (retry2 > options.maxRetries) {
+          return {
+            error: e
+          };
+        }
+      }
+      failIfAborted(api.signal);
+      try {
+        await options.backoff(retry2, options.maxRetries, api.signal);
+      } catch (backoffError) {
+        failIfAborted(api.signal);
+        throw backoffError;
+      }
+    }
+  }
+};
+var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
+  fail
+});
+
+// src/query/core/setupListeners.ts
+var INTERNAL_PREFIX = "__rtkq/";
+var ONLINE = "online";
+var OFFLINE = "offline";
+var FOCUS = "focus";
+var FOCUSED = "focused";
+var VISIBILITYCHANGE = "visibilitychange";
+var onFocus = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}${FOCUSED}`);
+var onFocusLost = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}un${FOCUSED}`);
+var onOnline = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}${ONLINE}`);
+var onOffline = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}${OFFLINE}`);
+var actions = {
+  onFocus,
+  onFocusLost,
+  onOnline,
+  onOffline
+};
+var initialized = false;
+function setupListeners(dispatch, customHandler) {
+  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) {
+        let updateListeners2 = function(add) {
+          Object.entries(handlers).forEach(([event, handler]) => {
+            if (add) {
+              window.addEventListener(event, handler, false);
+            } else {
+              window.removeEventListener(event, handler);
+            }
+          });
+        };
+        var updateListeners = updateListeners2;
+        const handlers = {
+          [FOCUS]: handleFocus,
+          [VISIBILITYCHANGE]: handleVisibilityChange,
+          [ONLINE]: handleOnline,
+          [OFFLINE]: handleOffline
+        };
+        updateListeners2(true);
+        initialized = true;
+        unsubscribe = () => {
+          updateListeners2(false);
+          initialized = false;
+        };
+      }
+    }
+    return unsubscribe;
+  }
+  return customHandler ? customHandler(dispatch, actions) : defaultHandler();
+}
+
+// src/query/endpointDefinitions.ts
+var ENDPOINT_QUERY = "query" /* query */;
+var ENDPOINT_MUTATION = "mutation" /* mutation */;
+var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
+function isQueryDefinition(e) {
+  return e.type === ENDPOINT_QUERY;
+}
+function isMutationDefinition(e) {
+  return e.type === ENDPOINT_MUTATION;
+}
+function isInfiniteQueryDefinition(e) {
+  return e.type === ENDPOINT_INFINITEQUERY;
+}
+function isAnyQueryDefinition(e) {
+  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);
+}
+function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
+  const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
+  if (finalDescription) {
+    return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
+  }
+  return [];
+}
+function isFunction(t) {
+  return typeof t === "function";
+}
+function expandTagDescription(description) {
+  return typeof description === "string" ? {
+    type: description
+  } : description;
+}
+
+// src/query/utils/immerImports.ts
+var import_immer = require("immer");
+
+// src/query/core/buildInitiate.ts
+var import_toolkit2 = require("@reduxjs/toolkit");
+
+// src/tsHelpers.ts
+function asSafePromise(promise, fallback) {
+  return promise.catch(fallback);
+}
+
+// src/query/apiTypes.ts
+var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
+
+// src/query/core/buildInitiate.ts
+var forceQueryFnSymbol = Symbol("forceQueryFn");
+var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
+function buildInitiate({
+  serializeQueryArgs,
+  queryThunk,
+  infiniteQueryThunk,
+  mutationThunk,
+  api,
+  context,
+  getInternalState
+}) {
+  const getRunningQueries = (dispatch) => getInternalState(dispatch)?.runningQueries;
+  const getRunningMutations = (dispatch) => getInternalState(dispatch)?.runningMutations;
+  const {
+    unsubscribeQueryResult,
+    removeMutationResult,
+    updateSubscriptionOptions
+  } = api.internalActions;
+  return {
+    buildInitiateQuery,
+    buildInitiateInfiniteQuery,
+    buildInitiateMutation,
+    getRunningQueryThunk,
+    getRunningMutationThunk,
+    getRunningQueriesThunk,
+    getRunningMutationsThunk
+  };
+  function getRunningQueryThunk(endpointName, queryArgs) {
+    return (dispatch) => {
+      const endpointDefinition = getEndpointDefinition(context, endpointName);
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      });
+      return getRunningQueries(dispatch)?.get(queryCacheKey);
+    };
+  }
+  function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
+    return (dispatch) => {
+      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId);
+    };
+  }
+  function getRunningQueriesThunk() {
+    return (dispatch) => filterNullishValues(getRunningQueries(dispatch));
+  }
+  function getRunningMutationsThunk() {
+    return (dispatch) => filterNullishValues(getRunningMutations(dispatch));
+  }
+  function middlewareWarning(dispatch) {
+    if (true) {
+      if (middlewareWarning.triggered) return;
+      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
+      middlewareWarning.triggered = true;
+      if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
+        throw new Error(false ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+You must add the middleware for RTK-Query to function correctly!`);
+      }
+    }
+  }
+  function buildInitiateAnyQuery(endpointName, endpointDefinition) {
+    const queryAction = (arg, {
+      subscribe = true,
+      forceRefetch,
+      subscriptionOptions,
+      [forceQueryFnSymbol]: forceQueryFn,
+      ...rest
+    } = {}) => (dispatch, getState) => {
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs: arg,
+        endpointDefinition,
+        endpointName
+      });
+      let thunk;
+      const commonThunkArgs = {
+        ...rest,
+        type: ENDPOINT_QUERY,
+        subscribe,
+        forceRefetch,
+        subscriptionOptions,
+        endpointName,
+        originalArgs: arg,
+        queryCacheKey,
+        [forceQueryFnSymbol]: forceQueryFn
+      };
+      if (isQueryDefinition(endpointDefinition)) {
+        thunk = queryThunk(commonThunkArgs);
+      } else {
+        const {
+          direction,
+          initialPageParam,
+          refetchCachedPages
+        } = rest;
+        thunk = infiniteQueryThunk({
+          ...commonThunkArgs,
+          // Supply these even if undefined. This helps with a field existence
+          // check over in `buildSlice.ts`
+          direction,
+          initialPageParam,
+          refetchCachedPages
+        });
+      }
+      const selector = api.endpoints[endpointName].select(arg);
+      const thunkResult = dispatch(thunk);
+      const stateAfter = selector(getState());
+      middlewareWarning(dispatch);
+      const {
+        requestId,
+        abort
+      } = thunkResult;
+      const skippedSynchronously = stateAfter.requestId !== requestId;
+      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);
+      const selectFromState = () => selector(getState());
+      const statePromise = Object.assign(forceQueryFn ? (
+        // a query has been forced (upsertQueryData)
+        // -> we want to resolve it once data has been written with the data that will be written
+        thunkResult.then(selectFromState)
+      ) : skippedSynchronously && !runningQuery ? (
+        // a query has been skipped due to a condition and we do not have any currently running query
+        // -> we want to resolve it immediately with the current data
+        Promise.resolve(stateAfter)
+      ) : (
+        // query just started or one is already in flight
+        // -> wait for the running query, then resolve with data from after that
+        Promise.all([runningQuery, thunkResult]).then(selectFromState)
+      ), {
+        arg,
+        requestId,
+        subscriptionOptions,
+        queryCacheKey,
+        abort,
+        async unwrap() {
+          const result = await statePromise;
+          if (result.isError) {
+            throw result.error;
+          }
+          return result.data;
+        },
+        refetch: (options) => dispatch(queryAction(arg, {
+          subscribe: false,
+          forceRefetch: true,
+          ...options
+        })),
+        unsubscribe() {
+          if (subscribe) dispatch(unsubscribeQueryResult({
+            queryCacheKey,
+            requestId
+          }));
+        },
+        updateSubscriptionOptions(options) {
+          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, endpointDefinition) {
+    const queryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
+    return queryAction;
+  }
+  function buildInitiateInfiniteQuery(endpointName, endpointDefinition) {
+    const infiniteQueryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
+    return infiniteQueryAction;
+  }
+  function buildInitiateMutation(endpointName) {
+    return (arg, {
+      track = true,
+      fixedCacheKey
+    } = {}) => (dispatch, getState) => {
+      const thunk = mutationThunk({
+        type: "mutation",
+        endpointName,
+        originalArgs: arg,
+        track,
+        fixedCacheKey
+      });
+      const thunkResult = dispatch(thunk);
+      middlewareWarning(dispatch);
+      const {
+        requestId,
+        abort,
+        unwrap
+      } = thunkResult;
+      const returnValuePromise = 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;
+    };
+  }
+}
+
+// src/query/standardSchema.ts
+var import_utils4 = require("@standard-schema/utils");
+var NamedSchemaError = class extends import_utils4.SchemaError {
+  constructor(issues, value, schemaName, _bqMeta) {
+    super(issues);
+    this.value = value;
+    this.schemaName = schemaName;
+    this._bqMeta = _bqMeta;
+  }
+};
+var shouldSkip = (skipSchemaValidation, schemaName) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;
+async function parseWithSchema(schema, data, schemaName, bqMeta) {
+  const result = await schema["~standard"].validate(data);
+  if (result.issues) {
+    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);
+  }
+  return result.value;
+}
+
+// src/query/core/buildThunks.ts
+function defaultTransformResponse(baseQueryReturnValue) {
+  return baseQueryReturnValue;
+}
+var addShouldAutoBatch = (arg = {}) => {
+  return {
+    ...arg,
+    [import_toolkit.SHOULD_AUTOBATCH]: true
+  };
+};
+function buildThunks({
+  reducerPath,
+  baseQuery,
+  context: {
+    endpointDefinitions
+  },
+  serializeQueryArgs,
+  api,
+  assertTagType,
+  selectors,
+  onSchemaFailure,
+  catchSchemaFailure: globalCatchSchemaFailure,
+  skipSchemaValidation: globalSkipSchemaValidation
+}) {
+  const patchQueryData = (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()
+    );
+    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
+    dispatch(api.internalActions.updateProvidedBy([{
+      queryCacheKey,
+      providedTags
+    }]));
+  };
+  function addToStart(items, item, max = 0) {
+    const newItems = [item, ...items];
+    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
+  }
+  function addToEnd(items, item, max = 0) {
+    const newItems = [...items, item];
+    return max && newItems.length > max ? newItems.slice(1) : newItems;
+  }
+  const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
+    const endpointDefinition = api.endpoints[endpointName];
+    const currentState = endpointDefinition.select(arg)(
+      // Work around TS 4.1 mismatch
+      getState()
+    );
+    const ret = {
+      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 ((0, import_immer.isDraftable)(currentState.data)) {
+        const [value, patches, inversePatches] = (0, import_immer.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 = (endpointName, arg, value) => (dispatch) => {
+    const res = dispatch(api.endpoints[endpointName].initiate(arg, {
+      subscribe: false,
+      forceRefetch: true,
+      [forceQueryFnSymbol]: () => ({
+        data: value
+      })
+    }));
+    return res;
+  };
+  const getTransformCallbackForEndpoint = (endpointDefinition, transformFieldName) => {
+    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName] : defaultTransformResponse;
+  };
+  const executeEndpoint = 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 = defaultTransformResponse;
+      const baseQueryApi = {
+        signal,
+        abort,
+        dispatch,
+        getState,
+        extra,
+        endpoint: arg.endpointName,
+        type: arg.type,
+        forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
+        queryCacheKey: isQuery ? arg.queryCacheKey : void 0
+      };
+      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
+      let finalQueryReturnValue;
+      const fetchPage = async (data, param, maxPages, previous) => {
+        if (param == null && data.pages.length) {
+          return Promise.resolve({
+            data
+          });
+        }
+        const finalQueryArg = {
+          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
+        };
+      };
+      async function executeRequest(finalQueryArg) {
+        let result;
+        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) {
+          result = forceQueryFn();
+        } else if (endpointDefinition.query) {
+          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformResponse");
+          result = await baseQuery(endpointDefinition.query(finalQueryArg), baseQueryApi, extraOptions);
+        } else {
+          result = await endpointDefinition.queryFn(finalQueryArg, baseQueryApi, extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, extraOptions));
+        }
+        if (typeof process !== "undefined" && true) {
+          const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
+          let err;
+          if (!result) {
+            err = `${what} did not return anything.`;
+          } else if (typeof result !== "object") {
+            err = `${what} did not return an object.`;
+          } else if (result.error && result.data) {
+            err = `${what} returned an object containing both \`error\` and \`result\`.`;
+          } else if (result.error === void 0 && result.data === void 0) {
+            err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
+          } else {
+            for (const key of Object.keys(result)) {
+              if (key !== "error" && key !== "data" && key !== "meta") {
+                err = `The object returned by ${what} has the unknown property ${key}.`;
+                break;
+              }
+            }
+          }
+          if (err) {
+            console.error(`Error encountered handling the endpoint ${arg.endpointName}.
+                  ${err}
+                  It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
+                  Object returned was:`, result);
+          }
+        }
+        if (result.error) throw new HandledError(result.error, result.meta);
+        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) {
+        const {
+          infiniteQueryOptions
+        } = endpointDefinition;
+        const {
+          maxPages = Infinity
+        } = infiniteQueryOptions;
+        const refetchCachedPages = arg.refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;
+        let result;
+        const blankData = {
+          pages: [],
+          pageParams: []
+        };
+        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data;
+        const isForcedQueryNeedingRefetch = (
+          // arg.forceRefetch
+          isForcedQuery(arg, getState()) && !arg.direction
+        );
+        const existingData = isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData;
+        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 {
+          const {
+            initialPageParam = infiniteQueryOptions.initialPageParam
+          } = arg;
+          const cachedPageParams = cachedData?.pageParams ?? [];
+          const firstPageParam = cachedPageParams[0] ?? initialPageParam;
+          const totalPages = cachedPageParams.length;
+          result = await fetchPage(existingData, firstPageParam, maxPages);
+          if (forceQueryFn) {
+            result = {
+              data: result.data.pages[0]
+            };
+          }
+          if (refetchCachedPages) {
+            for (let i = 1; i < totalPages; i++) {
+              const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
+              result = await fetchPage(result.data, param, maxPages);
+            }
+          }
+        }
+        finalQueryReturnValue = result;
+      } else {
+        finalQueryReturnValue = await executeRequest(arg.originalArgs);
+      }
+      if (metaSchema && !shouldSkip(skipSchemaValidation, "meta") && finalQueryReturnValue.meta) {
+        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, "metaSchema", finalQueryReturnValue.meta);
+      }
+      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 = {
+            endpoint: arg.endpointName,
+            arg: arg.originalArgs,
+            type: arg.type,
+            queryCacheKey: isQuery ? arg.queryCacheKey : void 0
+          };
+          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" && true) {
+        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, state) {
+    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 refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
+    }
+    return false;
+  }
+  const createQueryThunk = () => {
+    const generatedQueryThunk = (0, import_toolkit.createAsyncThunk)(`${reducerPath}/executeQuery`, executeEndpoint, {
+      getPendingMeta({
+        arg
+      }) {
+        const endpointDefinition = endpointDefinitions[arg.endpointName];
+        return addShouldAutoBatch({
+          startedTimeStamp: Date.now(),
+          ...isInfiniteQueryDefinition(endpointDefinition) ? {
+            direction: arg.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.direction;
+        if (isUpsertQuery(queryThunkArg)) {
+          return true;
+        }
+        if (requestState?.status === "pending") {
+          return false;
+        }
+        if (isForcedQuery(queryThunkArg, state)) {
+          return true;
+        }
+        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
+          currentArg,
+          previousArg,
+          endpointState: requestState,
+          state
+        })) {
+          return true;
+        }
+        if (fulfilledVal && !direction) {
+          return false;
+        }
+        return true;
+      },
+      dispatchConditionRejection: true
+    });
+    return generatedQueryThunk;
+  };
+  const queryThunk = createQueryThunk();
+  const infiniteQueryThunk = createQueryThunk();
+  const mutationThunk = (0, import_toolkit.createAsyncThunk)(`${reducerPath}/executeMutation`, executeEndpoint, {
+    getPendingMeta() {
+      return addShouldAutoBatch({
+        startedTimeStamp: Date.now()
+      });
+    }
+  });
+  const hasTheForce = (options) => "force" in options;
+  const hasMaxAge = (options) => "ifOlderThan" in options;
+  const prefetch = (endpointName, arg, options = {}) => (dispatch, getState) => {
+    const force = hasTheForce(options) && options.force;
+    const maxAge = hasMaxAge(options) && options.ifOlderThan;
+    const queryAction = (force2 = true) => {
+      const options2 = {
+        forceRefetch: force2,
+        subscribe: false
+      };
+      return api.endpoints[endpointName].initiate(arg, options2);
+    };
+    const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
+    if (force) {
+      dispatch(queryAction());
+    } else if (maxAge) {
+      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
+      if (!lastFulfilledTs) {
+        dispatch(queryAction());
+        return;
+      }
+      const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
+      if (shouldRetrigger) {
+        dispatch(queryAction());
+      }
+    } else {
+      dispatch(queryAction(false));
+    }
+  };
+  function matchesEndpoint(endpointName) {
+    return (action) => action?.meta?.arg?.endpointName === endpointName;
+  }
+  function buildMatchThunkActions(thunk, endpointName) {
+    return {
+      matchPending: (0, import_toolkit.isAllOf)((0, import_toolkit.isPending)(thunk), matchesEndpoint(endpointName)),
+      matchFulfilled: (0, import_toolkit.isAllOf)((0, import_toolkit.isFulfilled)(thunk), matchesEndpoint(endpointName)),
+      matchRejected: (0, import_toolkit.isAllOf)((0, import_toolkit.isRejected)(thunk), matchesEndpoint(endpointName))
+    };
+  }
+  return {
+    queryThunk,
+    mutationThunk,
+    infiniteQueryThunk,
+    prefetch,
+    updateQueryData,
+    upsertQueryData,
+    patchQueryData,
+    buildMatchThunkActions
+  };
+}
+function getNextPageParam(options, {
+  pages,
+  pageParams
+}, queryArg) {
+  const lastIndex = pages.length - 1;
+  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);
+}
+function getPreviousPageParam(options, {
+  pages,
+  pageParams
+}, queryArg) {
+  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);
+}
+function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
+  return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], (0, import_toolkit.isFulfilled)(action) ? action.payload : void 0, (0, import_toolkit.isRejectedWithValue)(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
+}
+
+// src/query/utils/getCurrent.ts
+function getCurrent(value) {
+  return (0, import_immer.isDraft)(value) ? (0, import_immer.current)(value) : value;
+}
+
+// src/query/core/buildSlice.ts
+function updateQuerySubstateIfExists(state, queryCacheKey, update) {
+  const substate = state[queryCacheKey];
+  if (substate) {
+    update(substate);
+  }
+}
+function getMutationCacheKey(id) {
+  return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
+}
+function updateMutationSubstateIfExists(state, id, update) {
+  const substate = state[getMutationCacheKey(id)];
+  if (substate) {
+    update(substate);
+  }
+}
+var initialState = {};
+function buildSlice({
+  reducerPath,
+  queryThunk,
+  mutationThunk,
+  serializeQueryArgs,
+  context: {
+    endpointDefinitions: definitions,
+    apiUid,
+    extractRehydrationInfo,
+    hasRehydrationInfo
+  },
+  assertTagType,
+  config
+}) {
+  const resetApiState = (0, import_toolkit.createAction)(`${reducerPath}/resetApiState`);
+  function writePendingCacheEntry(draft, arg, upserting, meta) {
+    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 !== void 0) {
+        substate.originalArgs = arg.originalArgs;
+      }
+      substate.startedTimeStamp = meta.startedTimeStamp;
+      const endpointDefinition = definitions[meta.arg.endpointName];
+      if (isInfiniteQueryDefinition(endpointDefinition) && "direction" in arg) {
+        ;
+        substate.direction = arg.direction;
+      }
+    });
+  }
+  function writeFulfilledCacheEntry(draft, meta, payload, upserting) {
+    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
+      if (substate.requestId !== meta.requestId && !upserting) return;
+      const {
+        merge
+      } = definitions[meta.arg.endpointName];
+      substate.status = STATUS_FULFILLED;
+      if (merge) {
+        if (substate.data !== void 0) {
+          const {
+            fulfilledTimeStamp,
+            arg,
+            baseQueryMeta,
+            requestId
+          } = meta;
+          let newData = (0, import_toolkit.createNextState)(substate.data, (draftSubstateData) => {
+            return merge(draftSubstateData, payload, {
+              arg: arg.originalArgs,
+              baseQueryMeta,
+              fulfilledTimeStamp,
+              requestId
+            });
+          });
+          substate.data = newData;
+        } else {
+          substate.data = payload;
+        }
+      } else {
+        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing((0, import_immer.isDraft)(substate.data) ? (0, import_immer.original)(substate.data) : substate.data, payload) : payload;
+      }
+      delete substate.error;
+      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
+    });
+  }
+  const querySlice = (0, import_toolkit.createSlice)({
+    name: `${reducerPath}/queries`,
+    initialState,
+    reducers: {
+      removeQueryResult: {
+        reducer(draft, {
+          payload: {
+            queryCacheKey
+          }
+        }) {
+          delete draft[queryCacheKey];
+        },
+        prepare: (0, import_toolkit.prepareAutoBatched)()
+      },
+      cacheEntriesUpserted: {
+        reducer(draft, action) {
+          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) => {
+          const queryDescriptions = payload.map((entry) => {
+            const {
+              endpointName,
+              arg,
+              value
+            } = entry;
+            const endpointDefinition = definitions[endpointName];
+            const queryDescription = {
+              type: ENDPOINT_QUERY,
+              endpointName,
+              originalArgs: entry.arg,
+              queryCacheKey: serializeQueryArgs({
+                queryArgs: arg,
+                endpointDefinition,
+                endpointName
+              })
+            };
+            return {
+              queryDescription,
+              value
+            };
+          });
+          const result = {
+            payload: queryDescriptions,
+            meta: {
+              [import_toolkit.SHOULD_AUTOBATCH]: true,
+              requestId: (0, import_toolkit.nanoid)(),
+              timestamp: Date.now()
+            }
+          };
+          return result;
+        }
+      },
+      queryResultPatched: {
+        reducer(draft, {
+          payload: {
+            queryCacheKey,
+            patches
+          }
+        }) {
+          updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
+            substate.data = (0, import_immer.applyPatches)(substate.data, patches.concat());
+          });
+        },
+        prepare: (0, import_toolkit.prepareAutoBatched)()
+      }
+    },
+    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) {
+          } else {
+            if (substate.requestId !== requestId) return;
+            substate.status = STATUS_REJECTED;
+            substate.error = payload ?? error;
+          }
+        });
+      }).addMatcher(hasRehydrationInfo, (draft, action) => {
+        const {
+          queries
+        } = extractRehydrationInfo(action);
+        for (const [key, entry] of Object.entries(queries)) {
+          if (
+            // do not rehydrate entries that were currently in flight.
+            entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED
+          ) {
+            draft[key] = entry;
+          }
+        }
+      });
+    }
+  });
+  const mutationSlice = (0, import_toolkit.createSlice)({
+    name: `${reducerPath}/mutations`,
+    initialState,
+    reducers: {
+      removeMutationResult: {
+        reducer(draft, {
+          payload
+        }) {
+          const cacheKey = getMutationCacheKey(payload);
+          if (cacheKey in draft) {
+            delete draft[cacheKey];
+          }
+        },
+        prepare: (0, import_toolkit.prepareAutoBatched)()
+      }
+    },
+    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;
+        });
+      }).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;
+          }
+        }
+      });
+    }
+  });
+  const initialInvalidationState = {
+    tags: {},
+    keys: {}
+  };
+  const invalidationSlice = (0, import_toolkit.createSlice)({
+    name: `${reducerPath}/invalidation`,
+    initialState: initialInvalidationState,
+    reducers: {
+      updateProvidedBy: {
+        reducer(draft, action) {
+          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);
+              }
+            }
+            draft.keys[queryCacheKey] = providedTags;
+          }
+        },
+        prepare: (0, import_toolkit.prepareAutoBatched)()
+      }
+    },
+    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((0, import_toolkit.isAnyOf)((0, import_toolkit.isFulfilled)(queryThunk), (0, import_toolkit.isRejectedWithValue)(queryThunk)), (draft, action) => {
+        writeProvidedTagsForQueries(draft, [action]);
+      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {
+        const mockActions = action.payload.map(({
+          queryDescription,
+          value
+        }) => {
+          return {
+            type: "UNKNOWN",
+            payload: value,
+            meta: {
+              requestStatus: "fulfilled",
+              requestId: "UNKNOWN",
+              arg: queryDescription
+            }
+          };
+        });
+        writeProvidedTagsForQueries(draft, mockActions);
+      });
+    }
+  });
+  function removeCacheKeyFromTags(draft, queryCacheKey) {
+    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);
+    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, actions3) {
+    const providedByEntries = actions3.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));
+  }
+  const subscriptionSlice = (0, import_toolkit.createSlice)({
+    name: `${reducerPath}/subscriptions`,
+    initialState,
+    reducers: {
+      updateSubscriptionOptions(d, a) {
+      },
+      unsubscribeQueryResult(d, a) {
+      },
+      internal_getRTKQSubscriptions() {
+      }
+    }
+  });
+  const internalSubscriptionsSlice = (0, import_toolkit.createSlice)({
+    name: `${reducerPath}/internalSubscriptions`,
+    initialState,
+    reducers: {
+      subscriptionsUpdated: {
+        reducer(state, action) {
+          return (0, import_immer.applyPatches)(state, action.payload);
+        },
+        prepare: (0, import_toolkit.prepareAutoBatched)()
+      }
+    }
+  });
+  const configSlice = (0, import_toolkit.createSlice)({
+    name: `${reducerPath}/config`,
+    initialState: {
+      online: isOnline(),
+      focused: isDocumentVisible(),
+      middlewareRegistered: false,
+      ...config
+    },
+    reducers: {
+      middlewareRegistered(state, {
+        payload
+      }) {
+        state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
+      }
+    },
+    extraReducers: (builder) => {
+      builder.addCase(onOnline, (state) => {
+        state.online = true;
+      }).addCase(onOffline, (state) => {
+        state.online = false;
+      }).addCase(onFocus, (state) => {
+        state.focused = true;
+      }).addCase(onFocusLost, (state) => {
+        state.focused = false;
+      }).addMatcher(hasRehydrationInfo, (draft) => ({
+        ...draft
+      }));
+    }
+  });
+  const combinedReducer = (0, import_toolkit.combineReducers)({
+    queries: querySlice.reducer,
+    mutations: mutationSlice.reducer,
+    provided: invalidationSlice.reducer,
+    subscriptions: internalSubscriptionsSlice.reducer,
+    config: configSlice.reducer
+  });
+  const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
+  const actions2 = {
+    ...configSlice.actions,
+    ...querySlice.actions,
+    ...subscriptionSlice.actions,
+    ...internalSubscriptionsSlice.actions,
+    ...mutationSlice.actions,
+    ...invalidationSlice.actions,
+    resetApiState
+  };
+  return {
+    reducer,
+    actions: actions2
+  };
+}
+
+// src/query/core/buildSelectors.ts
+var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
+var initialSubState = {
+  status: STATUS_UNINITIALIZED
+};
+var defaultQuerySubState = /* @__PURE__ */ (0, import_toolkit.createNextState)(initialSubState, () => {
+});
+var defaultMutationSubState = /* @__PURE__ */ (0, import_toolkit.createNextState)(initialSubState, () => {
+});
+function buildSelectors({
+  serializeQueryArgs,
+  reducerPath,
+  createSelector: createSelector2
+}) {
+  const selectSkippedQuery = (state) => defaultQuerySubState;
+  const selectSkippedMutation = (state) => defaultMutationSubState;
+  return {
+    buildQuerySelector,
+    buildInfiniteQuerySelector,
+    buildMutationSelector,
+    selectInvalidatedBy,
+    selectCachedArgsForQuery,
+    selectApiState,
+    selectQueries,
+    selectMutations,
+    selectQueryEntry,
+    selectConfig
+  };
+  function withRequestFlags(substate) {
+    return {
+      ...substate,
+      ...getRequestStatusFlags(substate.status)
+    };
+  }
+  function selectApiState(rootState) {
+    const state = rootState[reducerPath];
+    if (true) {
+      if (!state) {
+        if (selectApiState.triggered) return state;
+        selectApiState.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) {
+    return selectApiState(rootState)?.queries;
+  }
+  function selectQueryEntry(rootState, cacheKey) {
+    return selectQueries(rootState)?.[cacheKey];
+  }
+  function selectMutations(rootState) {
+    return selectApiState(rootState)?.mutations;
+  }
+  function selectConfig(rootState) {
+    return selectApiState(rootState)?.config;
+  }
+  function buildAnyQuerySelector(endpointName, endpointDefinition, combiner) {
+    return (queryArgs) => {
+      if (queryArgs === skipToken) {
+        return createSelector2(selectSkippedQuery, combiner);
+      }
+      const serializedArgs = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      });
+      const selectQuerySubstate = (state) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;
+      return createSelector2(selectQuerySubstate, combiner);
+    };
+  }
+  function buildQuerySelector(endpointName, endpointDefinition) {
+    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags);
+  }
+  function buildInfiniteQuerySelector(endpointName, endpointDefinition) {
+    const {
+      infiniteQueryOptions
+    } = endpointDefinition;
+    function withInfiniteQueryResultFlags(substate) {
+      const stateWithRequestFlags = {
+        ...substate,
+        ...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);
+  }
+  function buildMutationSelector() {
+    return (id) => {
+      let mutationId;
+      if (typeof id === "object") {
+        mutationId = getMutationCacheKey(id) ?? skipToken;
+      } else {
+        mutationId = id;
+      }
+      const selectMutationSubstate = (state) => selectApiState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
+      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
+      return createSelector2(finalSelectMutationSubstate, withRequestFlags);
+    };
+  }
+  function selectInvalidatedBy(state, tags) {
+    const apiState = state[reducerPath];
+    const toInvalidate = /* @__PURE__ */ new Set();
+    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 !== void 0 ? (
+        // 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(state, queryName) {
+    return filterMap(Object.values(selectQueries(state)), (entry) => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
+  }
+  function getHasNextPage(options, data, queryArg) {
+    if (!data) return false;
+    return getNextPageParam(options, data, queryArg) != null;
+  }
+  function getHasPreviousPage(options, data, queryArg) {
+    if (!data || !options.getPreviousPageParam) return false;
+    return getPreviousPageParam(options, data, queryArg) != null;
+  }
+}
+
+// src/query/createApi.ts
+var import_toolkit3 = require("@reduxjs/toolkit");
+
+// src/query/defaultSerializeQueryArgs.ts
+var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
+var defaultSerializeQueryArgs = ({
+  endpointName,
+  queryArgs
+}) => {
+  let serialized = "";
+  const cached = cache?.get(queryArgs);
+  if (typeof cached === "string") {
+    serialized = cached;
+  } else {
+    const stringified = JSON.stringify(queryArgs, (key, value) => {
+      value = typeof value === "bigint" ? {
+        $bigint: value.toString()
+      } : value;
+      value = (0, import_toolkit.isPlainObject)(value) ? Object.keys(value).sort().reduce((acc, key2) => {
+        acc[key2] = value[key2];
+        return acc;
+      }, {}) : value;
+      return value;
+    });
+    if ((0, import_toolkit.isPlainObject)(queryArgs)) {
+      cache?.set(queryArgs, stringified);
+    }
+    serialized = stringified;
+  }
+  return `${endpointName}(${serialized})`;
+};
+
+// src/query/createApi.ts
+var import_reselect = require("reselect");
+function buildCreateApi(...modules) {
+  return function baseCreateApi(options) {
+    const extractRehydrationInfo = (0, import_reselect.weakMapMemoize)((action) => options.extractRehydrationInfo?.(action, {
+      reducerPath: options.reducerPath ?? "api"
+    }));
+    const optionsWithDefaults = {
+      reducerPath: "api",
+      keepUnusedDataFor: 60,
+      refetchOnMountOrArgChange: false,
+      refetchOnFocus: false,
+      refetchOnReconnect: false,
+      invalidationBehavior: "delayed",
+      ...options,
+      extractRehydrationInfo,
+      serializeQueryArgs(queryArgsApi) {
+        let finalSerializeQueryArgs = defaultSerializeQueryArgs;
+        if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
+          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
+          finalSerializeQueryArgs = (queryArgsApi2) => {
+            const initialResult = endpointSQA(queryArgsApi2);
+            if (typeof initialResult === "string") {
+              return initialResult;
+            } else {
+              return defaultSerializeQueryArgs({
+                ...queryArgsApi2,
+                queryArgs: initialResult
+              });
+            }
+          };
+        } else if (options.serializeQueryArgs) {
+          finalSerializeQueryArgs = options.serializeQueryArgs;
+        }
+        return finalSerializeQueryArgs(queryArgsApi);
+      },
+      tagTypes: [...options.tagTypes || []]
+    };
+    const context = {
+      endpointDefinitions: {},
+      batch(fn) {
+        fn();
+      },
+      apiUid: (0, import_toolkit.nanoid)(),
+      extractRehydrationInfo,
+      hasRehydrationInfo: (0, import_reselect.weakMapMemoize)((action) => extractRehydrationInfo(action) != null)
+    };
+    const api = {
+      injectEndpoints,
+      enhanceEndpoints({
+        addTagTypes,
+        endpoints
+      }) {
+        if (addTagTypes) {
+          for (const eT of addTagTypes) {
+            if (!optionsWithDefaults.tagTypes.includes(eT)) {
+              ;
+              optionsWithDefaults.tagTypes.push(eT);
+            }
+          }
+        }
+        if (endpoints) {
+          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
+            if (typeof partialDefinition === "function") {
+              partialDefinition(getEndpointDefinition(context, endpointName));
+            } else {
+              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
+            }
+          }
+        }
+        return api;
+      }
+    };
+    const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
+    function injectEndpoints(inject) {
+      const evaluatedEndpoints = inject.endpoints({
+        query: (x) => ({
+          ...x,
+          type: ENDPOINT_QUERY
+        }),
+        mutation: (x) => ({
+          ...x,
+          type: ENDPOINT_MUTATION
+        }),
+        infiniteQuery: (x) => ({
+          ...x,
+          type: ENDPOINT_INFINITEQUERY
+        })
+      });
+      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
+        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
+          if (inject.overrideExisting === "throw") {
+            throw new Error(false ? _formatProdErrorMessage2(39) : `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
+          } else if (typeof process !== "undefined" && true) {
+            console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
+          }
+          continue;
+        }
+        if (typeof process !== "undefined" && true) {
+          if (isInfiniteQueryDefinition(definition)) {
+            const {
+              infiniteQueryOptions
+            } = definition;
+            const {
+              maxPages,
+              getPreviousPageParam: getPreviousPageParam2
+            } = infiniteQueryOptions;
+            if (typeof maxPages === "number") {
+              if (maxPages < 1) {
+                throw new Error(false ? _formatProdErrorMessage22(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);
+              }
+              if (typeof getPreviousPageParam2 !== "function") {
+                throw new Error(false ? _formatProdErrorMessage3(41) : `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;
+    }
+    return api.injectEndpoints({
+      endpoints: options.endpoints
+    });
+  };
+}
+
+// src/query/fakeBaseQuery.ts
+var import_toolkit4 = require("@reduxjs/toolkit");
+var _NEVER = /* @__PURE__ */ Symbol();
+function fakeBaseQuery() {
+  return function() {
+    throw new Error(false ? _formatProdErrorMessage4(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
+  };
+}
+
+// src/query/tsHelpers.ts
+function assertCast(v) {
+}
+function safeAssign(target, ...args) {
+  return Object.assign(target, ...args);
+}
+
+// src/query/core/buildMiddleware/batchActions.ts
+var buildBatchedActionsHandler = ({
+  api,
+  queryThunk,
+  internalState,
+  mwApi
+}) => {
+  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
+  let previousSubscriptions = null;
+  let updateSyncTimer = null;
+  const {
+    updateSubscriptionOptions,
+    unsubscribeQueryResult
+  } = api.internalActions;
+  const actuallyMutateSubscriptions = (currentSubscriptions, 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) => {
+    const subscriptions = getSubscriptions();
+    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);
+    return subscriptionsForQueryArg?.size ?? 0;
+  };
+  const isRequestSubscribed = (queryCacheKey, requestId) => {
+    const subscriptions = getSubscriptions();
+    return !!subscriptions?.get(queryCacheKey)?.get(requestId);
+  };
+  const subscriptionSelectors = {
+    getSubscriptions,
+    getSubscriptionCount,
+    isRequestSubscribed
+  };
+  function serializeSubscriptions(currentSubscriptions) {
+    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));
+  }
+  return (action, mwApi2) => {
+    if (!previousSubscriptions) {
+      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
+    }
+    if (api.util.resetApiState.match(action)) {
+      previousSubscriptions = {};
+      internalState.currentSubscriptions.clear();
+      updateSyncTimer = null;
+      return [true, false];
+    }
+    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
+      return [false, subscriptionSelectors];
+    }
+    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
+    let actionShouldContinue = true;
+    if (false) {
+      return [false, internalState.currentPolls];
+    }
+    if (didMutate) {
+      if (!updateSyncTimer) {
+        updateSyncTimer = setTimeout(() => {
+          const newSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
+          const [, patches] = (0, import_immer.produceWithPatches)(previousSubscriptions, () => newSubscriptions);
+          mwApi2.next(api.internalActions.subscriptionsUpdated(patches));
+          previousSubscriptions = newSubscriptions;
+          updateSyncTimer = null;
+        }, 500);
+      }
+      const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
+      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
+      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
+    }
+    return [actionShouldContinue, false];
+  };
+};
+
+// src/query/core/buildMiddleware/cacheCollection.ts
+var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
+var buildCacheCollectionHandler = ({
+  reducerPath,
+  api,
+  queryThunk,
+  context,
+  internalState,
+  selectors: {
+    selectQueryEntry,
+    selectConfig
+  },
+  getRunningQueryThunk,
+  mwApi
+}) => {
+  const {
+    removeQueryResult,
+    unsubscribeQueryResult,
+    cacheEntriesUpserted
+  } = api.internalActions;
+  const canTriggerUnsubscribe = (0, import_toolkit.isAnyOf)(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);
+  function anySubscriptionsRemainingForKey(queryCacheKey) {
+    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);
+    if (!subscriptions) {
+      return false;
+    }
+    const hasSubscriptions = subscriptions.size > 0;
+    return hasSubscriptions;
+  }
+  const currentRemovalTimeouts = {};
+  function abortAllPromises(promiseMap) {
+    for (const promise of promiseMap.values()) {
+      promise?.abort?.();
+    }
+  }
+  const handler = (action, mwApi2) => {
+    const state = mwApi2.getState();
+    const config = selectConfig(state);
+    if (canTriggerUnsubscribe(action)) {
+      let queryCacheKeys;
+      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, mwApi2, 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);
+      handleUnsubscribeMany(Object.keys(queries), mwApi2, config);
+    }
+  };
+  function handleUnsubscribeMany(cacheKeys, api2, config) {
+    const state = api2.getState();
+    for (const queryCacheKey of cacheKeys) {
+      const entry = selectQueryEntry(state, queryCacheKey);
+      if (entry?.endpointName) {
+        handleUnsubscribe(queryCacheKey, entry.endpointName, api2, config);
+      }
+    }
+  }
+  function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName);
+    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
+    if (keepUnusedDataFor === Infinity) {
+      return;
+    }
+    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
+    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+      const currentTimeout = currentRemovalTimeouts[queryCacheKey];
+      if (currentTimeout) {
+        clearTimeout(currentTimeout);
+      }
+      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
+        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+          const entry = selectQueryEntry(api2.getState(), queryCacheKey);
+          if (entry?.endpointName) {
+            const runningQuery = api2.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));
+            runningQuery?.abort();
+          }
+          api2.dispatch(removeQueryResult({
+            queryCacheKey
+          }));
+        }
+        delete currentRemovalTimeouts[queryCacheKey];
+      }, finalKeepUnusedDataFor * 1e3);
+    }
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/cacheLifecycle.ts
+var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
+var buildCacheLifecycleHandler = ({
+  api,
+  reducerPath,
+  context,
+  queryThunk,
+  mutationThunk,
+  internalState,
+  selectors: {
+    selectQueryEntry,
+    selectApiState
+  }
+}) => {
+  const isQueryThunk = (0, import_toolkit.isAsyncThunkAction)(queryThunk);
+  const isMutationThunk = (0, import_toolkit.isAsyncThunkAction)(mutationThunk);
+  const isFulfilledThunk = (0, import_toolkit.isFulfilled)(queryThunk, mutationThunk);
+  const lifecycleMap = {};
+  const {
+    removeQueryResult,
+    removeMutationResult,
+    cacheEntriesUpserted
+  } = api.internalActions;
+  function resolveLifecycleEntry(cacheKey, data, meta) {
+    const lifecycle = lifecycleMap[cacheKey];
+    if (lifecycle?.valueResolved) {
+      lifecycle.valueResolved({
+        data,
+        meta
+      });
+      delete lifecycle.valueResolved;
+    }
+  }
+  function removeLifecycleEntry(cacheKey) {
+    const lifecycle = lifecycleMap[cacheKey];
+    if (lifecycle) {
+      delete lifecycleMap[cacheKey];
+      lifecycle.cacheEntryRemoved();
+    }
+  }
+  function getActionMetaFields(action) {
+    const {
+      arg,
+      requestId
+    } = action.meta;
+    const {
+      endpointName,
+      originalArgs
+    } = arg;
+    return [endpointName, originalArgs, requestId];
+  }
+  const handler = (action, mwApi, stateBefore) => {
+    const cacheKey = getCacheKey(action);
+    function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
+      const oldEntry = selectQueryEntry(stateBefore, cacheKey2);
+      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey2);
+      if (!oldEntry && newEntry) {
+        handleNewKey(endpointName, originalArgs, cacheKey2, 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 cacheKey2 of Object.keys(lifecycleMap)) {
+        removeLifecycleEntry(cacheKey2);
+      }
+    }
+  };
+  function getCacheKey(action) {
+    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, originalArgs, queryCacheKey, mwApi, requestId) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName);
+    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
+    if (!onCacheEntryAdded) return;
+    const lifecycle = {};
+    const cacheEntryRemoved = new Promise((resolve) => {
+      lifecycle.cacheEntryRemoved = resolve;
+    });
+    const cacheDataLoaded = Promise.race([new Promise((resolve) => {
+      lifecycle.valueResolved = resolve;
+    }), cacheEntryRemoved.then(() => {
+      throw neverResolvedError;
+    })]);
+    cacheDataLoaded.catch(() => {
+    });
+    lifecycleMap[queryCacheKey] = lifecycle;
+    const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);
+    const extra = mwApi.dispatch((_, __, extra2) => extra2);
+    const lifecycleApi = {
+      ...mwApi,
+      getCacheEntry: () => selector(mwApi.getState()),
+      requestId,
+      extra,
+      updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
+      cacheDataLoaded,
+      cacheEntryRemoved
+    };
+    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
+    Promise.resolve(runningHandler).catch((e) => {
+      if (e === neverResolvedError) return;
+      throw e;
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/devMiddleware.ts
+var buildDevCheckHandler = ({
+  api,
+  context: {
+    apiUid
+  },
+  reducerPath
+}) => {
+  return (action, mwApi) => {
+    if (api.util.resetApiState.match(action)) {
+      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
+    }
+    if (typeof process !== "undefined" && true) {
+      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
+        console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
+You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
+      }
+    }
+  };
+};
+
+// src/query/core/buildMiddleware/invalidationByTags.ts
+var buildInvalidationByTagsHandler = ({
+  reducerPath,
+  context,
+  context: {
+    endpointDefinitions
+  },
+  mutationThunk,
+  queryThunk,
+  api,
+  assertTagType,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    removeQueryResult
+  } = api.internalActions;
+  const isThunkActionWithTags = (0, import_toolkit.isAnyOf)((0, import_toolkit.isFulfilled)(mutationThunk), (0, import_toolkit.isRejectedWithValue)(mutationThunk));
+  const isQueryEnd = (0, import_toolkit.isAnyOf)((0, import_toolkit.isFulfilled)(queryThunk, mutationThunk), (0, import_toolkit.isRejected)(queryThunk, mutationThunk));
+  let pendingTagInvalidations = [];
+  let pendingRequestCount = 0;
+  const handler = (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, void 0, void 0, void 0, void 0, assertTagType), mwApi);
+    }
+  };
+  function hasPendingRequests() {
+    return pendingRequestCount > 0;
+  }
+  function invalidateTags(newTags, mwApi) {
+    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
+            }));
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            mwApi.dispatch(refetchQuery(querySubState));
+          }
+        }
+      }
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/polling.ts
+var buildPollingHandler = ({
+  reducerPath,
+  queryThunk,
+  api,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    currentPolls,
+    currentSubscriptions
+  } = internalState;
+  const pendingPollingUpdates = /* @__PURE__ */ new Set();
+  let pollingUpdateTimer = null;
+  const handler = (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();
+      if (pollingUpdateTimer) {
+        clearTimeout(pollingUpdateTimer);
+        pollingUpdateTimer = null;
+      }
+      pendingPollingUpdates.clear();
+    }
+  };
+  function schedulePollingUpdate(queryCacheKey, api2) {
+    pendingPollingUpdates.add(queryCacheKey);
+    if (!pollingUpdateTimer) {
+      pollingUpdateTimer = setTimeout(() => {
+        for (const key of pendingPollingUpdates) {
+          updatePollingInterval({
+            queryCacheKey: key
+          }, api2);
+        }
+        pendingPollingUpdates.clear();
+        pollingUpdateTimer = null;
+      }, 0);
+    }
+  }
+  function startNextPoll({
+    queryCacheKey
+  }, api2) {
+    const state = api2.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 = void 0;
+    }
+    const nextPollTimestamp = Date.now() + lowestPollingInterval;
+    currentPolls.set(queryCacheKey, {
+      nextPollTimestamp,
+      pollingInterval: lowestPollingInterval,
+      timeout: setTimeout(() => {
+        if (state.config.focused || !skipPollingIfUnfocused) {
+          api2.dispatch(refetchQuery(querySubState));
+        }
+        startNextPoll({
+          queryCacheKey
+        }, api2);
+      }, lowestPollingInterval)
+    });
+  }
+  function updatePollingInterval({
+    queryCacheKey
+  }, api2) {
+    const state = api2.getState()[reducerPath];
+    const querySubState = state.queries[queryCacheKey];
+    const subscriptions = currentSubscriptions.get(queryCacheKey);
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
+      return;
+    }
+    const {
+      lowestPollingInterval
+    } = findLowestPollingInterval(subscriptions);
+    if (false) {
+      const updateCounters = currentPolls.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
+      }, api2);
+    }
+  }
+  function cleanupPollForKey(key) {
+    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 = /* @__PURE__ */ new Map()) {
+    let skipPollingIfUnfocused = 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;
+};
+
+// src/query/core/buildMiddleware/queryLifecycle.ts
+var buildQueryLifecycleHandler = ({
+  api,
+  context,
+  queryThunk,
+  mutationThunk
+}) => {
+  const isPendingThunk = (0, import_toolkit.isPending)(queryThunk, mutationThunk);
+  const isRejectedThunk = (0, import_toolkit.isRejected)(queryThunk, mutationThunk);
+  const isFullfilledThunk = (0, import_toolkit.isFulfilled)(queryThunk, mutationThunk);
+  const lifecycleMap = {};
+  const handler = (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 = {};
+        const queryFulfilled = new Promise((resolve, reject) => {
+          lifecycle.resolve = resolve;
+          lifecycle.reject = reject;
+        });
+        queryFulfilled.catch(() => {
+        });
+        lifecycleMap[requestId] = lifecycle;
+        const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);
+        const extra = mwApi.dispatch((_, __, extra2) => extra2);
+        const lifecycleApi = {
+          ...mwApi,
+          getCacheEntry: () => selector(mwApi.getState()),
+          requestId,
+          extra,
+          updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
+          queryFulfilled
+        };
+        onQueryStarted(originalArgs, lifecycleApi);
+      }
+    } else if (isFullfilledThunk(action)) {
+      const {
+        requestId,
+        baseQueryMeta
+      } = action.meta;
+      lifecycleMap[requestId]?.resolve({
+        data: action.payload,
+        meta: baseQueryMeta
+      });
+      delete lifecycleMap[requestId];
+    } else if (isRejectedThunk(action)) {
+      const {
+        requestId,
+        rejectedWithValue,
+        baseQueryMeta
+      } = action.meta;
+      lifecycleMap[requestId]?.reject({
+        error: action.payload ?? action.error,
+        isUnhandledError: !rejectedWithValue,
+        meta: baseQueryMeta
+      });
+      delete lifecycleMap[requestId];
+    }
+  };
+  return handler;
+};
+
+// src/query/core/buildMiddleware/windowEventHandling.ts
+var buildWindowEventHandler = ({
+  reducerPath,
+  context,
+  api,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    removeQueryResult
+  } = api.internalActions;
+  const handler = (action, mwApi) => {
+    if (onFocus.match(action)) {
+      refetchValidQueries(mwApi, "refetchOnFocus");
+    }
+    if (onOnline.match(action)) {
+      refetchValidQueries(mwApi, "refetchOnReconnect");
+    }
+  };
+  function refetchValidQueries(api2, type) {
+    const state = api2.getState()[reducerPath];
+    const queries = state.queries;
+    const subscriptions = internalState.currentSubscriptions;
+    context.batch(() => {
+      for (const queryCacheKey of 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] === void 0) && state.config[type];
+        if (shouldRefetch) {
+          if (subscriptionSubState.size === 0) {
+            api2.dispatch(removeQueryResult({
+              queryCacheKey
+            }));
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            api2.dispatch(refetchQuery(querySubState));
+          }
+        }
+      }
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/index.ts
+function buildMiddleware(input) {
+  const {
+    reducerPath,
+    queryThunk,
+    api,
+    context,
+    getInternalState
+  } = input;
+  const {
+    apiUid
+  } = context;
+  const actions2 = {
+    invalidateTags: (0, import_toolkit.createAction)(`${reducerPath}/invalidateTags`)
+  };
+  const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
+  const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
+  const middleware = (mwApi) => {
+    let initialized2 = false;
+    const internalState = getInternalState(mwApi.dispatch);
+    const builderArgs = {
+      ...input,
+      internalState,
+      refetchQuery,
+      isThisApiSliceAction,
+      mwApi
+    };
+    const handlers = handlerBuilders.map((build) => build(builderArgs));
+    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);
+    const windowEventsHandler = buildWindowEventHandler(builderArgs);
+    return (next) => {
+      return (action) => {
+        if (!(0, import_toolkit.isAction)(action)) {
+          return next(action);
+        }
+        if (!initialized2) {
+          initialized2 = true;
+          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
+        }
+        const mwApiWithNext = {
+          ...mwApi,
+          next
+        };
+        const stateBefore = mwApi.getState();
+        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
+        let res;
+        if (actionShouldContinue) {
+          res = next(action);
+        } else {
+          res = internalProbeResult;
+        }
+        if (!!mwApi.getState()[reducerPath]) {
+          windowEventsHandler(action, mwApiWithNext, stateBefore);
+          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
+            for (const handler of handlers) {
+              handler(action, mwApiWithNext, stateBefore);
+            }
+          }
+        }
+        return res;
+      };
+    };
+  };
+  return {
+    middleware,
+    actions: actions2
+  };
+  function refetchQuery(querySubState) {
+    return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
+      subscribe: false,
+      forceRefetch: true
+    });
+  }
+}
+
+// src/query/core/module.ts
+var coreModuleName = /* @__PURE__ */ Symbol();
+var coreModule = ({
+  createSelector: createSelector2 = import_toolkit.createSelector
+} = {}) => ({
+  name: coreModuleName,
+  init(api, {
+    baseQuery,
+    tagTypes,
+    reducerPath,
+    serializeQueryArgs,
+    keepUnusedDataFor,
+    refetchOnMountOrArgChange,
+    refetchOnFocus,
+    refetchOnReconnect,
+    invalidationBehavior,
+    onSchemaFailure,
+    catchSchemaFailure,
+    skipSchemaValidation
+  }, context) {
+    (0, import_immer.enablePatches)();
+    assertCast(serializeQueryArgs);
+    const assertTagType = (tag) => {
+      if (typeof process !== "undefined" && true) {
+        if (!tagTypes.includes(tag.type)) {
+          console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
+        }
+      }
+      return tag;
+    };
+    Object.assign(api, {
+      reducerPath,
+      endpoints: {},
+      internalActions: {
+        onOnline,
+        onOffline,
+        onFocus,
+        onFocusLost
+      },
+      util: {}
+    });
+    const selectors = buildSelectors({
+      serializeQueryArgs,
+      reducerPath,
+      createSelector: createSelector2
+    });
+    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
+    });
+    safeAssign(api.internalActions, sliceActions);
+    const internalStateMap = /* @__PURE__ */ new WeakMap();
+    const getInternalState = (dispatch) => {
+      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
+        currentSubscriptions: /* @__PURE__ */ new Map(),
+        currentPolls: /* @__PURE__ */ new Map(),
+        runningQueries: /* @__PURE__ */ new Map(),
+        runningMutations: /* @__PURE__ */ new Map()
+      }));
+      return state;
+    };
+    const {
+      buildInitiateQuery,
+      buildInitiateInfiniteQuery,
+      buildInitiateMutation,
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueriesThunk,
+      getRunningQueryThunk
+    } = buildInitiate({
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      serializeQueryArgs,
+      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,
+      middleware
+    });
+    return {
+      name: coreModuleName,
+      injectEndpoint(endpointName, definition) {
+        const anyApi = api;
+        const endpoint = anyApi.endpoints[endpointName] ??= {};
+        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));
+        }
+      }
+    };
+  }
+});
+
+// src/query/core/index.ts
+var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+  NamedSchemaError,
+  QueryStatus,
+  _NEVER,
+  buildCreateApi,
+  copyWithStructuralSharing,
+  coreModule,
+  coreModuleName,
+  createApi,
+  defaultSerializeQueryArgs,
+  fakeBaseQuery,
+  fetchBaseQuery,
+  retry,
+  setupListeners,
+  skipToken
+});
+//# sourceMappingURL=rtk-query.development.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.development.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/query/index.ts","../../../src/query/core/apiState.ts","../../../src/query/core/rtkImports.ts","../../../src/query/utils/copyWithStructuralSharing.ts","../../../src/query/utils/filterMap.ts","../../../src/query/utils/isAbsoluteUrl.ts","../../../src/query/utils/isDocumentVisible.ts","../../../src/query/utils/isNotNullish.ts","../../../src/query/utils/isOnline.ts","../../../src/query/utils/joinUrls.ts","../../../src/query/utils/getOrInsert.ts","../../../src/query/utils/signals.ts","../../../src/query/fetchBaseQuery.ts","../../../src/query/HandledError.ts","../../../src/query/retry.ts","../../../src/query/core/setupListeners.ts","../../../src/query/endpointDefinitions.ts","../../../src/query/utils/immerImports.ts","../../../src/query/core/buildInitiate.ts","../../../src/tsHelpers.ts","../../../src/query/apiTypes.ts","../../../src/query/standardSchema.ts","../../../src/query/core/buildThunks.ts","../../../src/query/utils/getCurrent.ts","../../../src/query/core/buildSlice.ts","../../../src/query/core/buildSelectors.ts","../../../src/query/createApi.ts","../../../src/query/defaultSerializeQueryArgs.ts","../../../src/query/fakeBaseQuery.ts","../../../src/query/tsHelpers.ts","../../../src/query/core/buildMiddleware/batchActions.ts","../../../src/query/core/buildMiddleware/cacheCollection.ts","../../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../../src/query/core/buildMiddleware/devMiddleware.ts","../../../src/query/core/buildMiddleware/invalidationByTags.ts","../../../src/query/core/buildMiddleware/polling.ts","../../../src/query/core/buildMiddleware/queryLifecycle.ts","../../../src/query/core/buildMiddleware/windowEventHandling.ts","../../../src/query/core/buildMiddleware/index.ts","../../../src/query/core/module.ts","../../../src/query/core/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport type { CombinedState, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './core/apiState';\nexport { QueryStatus } from './core/apiState';\nexport type { Api, ApiContext, Module } from './apiTypes';\nexport type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nexport 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';\nexport { fetchBaseQuery } from './fetchBaseQuery';\nexport type { FetchBaseQueryArgs, FetchBaseQueryError, FetchBaseQueryMeta, FetchArgs } from './fetchBaseQuery';\nexport { retry } from './retry';\nexport type { RetryOptions } from './retry';\nexport { setupListeners } from './core/setupListeners';\nexport { skipToken } from './core/buildSelectors';\nexport type { QueryResultSelectorResult, MutationResultSelectorResult, SkipToken } from './core/buildSelectors';\nexport type { QueryActionCreatorResult, MutationActionCreatorResult, StartQueryActionCreatorOptions } from './core/buildInitiate';\nexport type { CreateApi, CreateApiOptions } from './createApi';\nexport { buildCreateApi } from './createApi';\nexport { _NEVER, fakeBaseQuery } from './fakeBaseQuery';\nexport { copyWithStructuralSharing } from './utils/copyWithStructuralSharing';\nexport { createApi, coreModule, coreModuleName } from './core/index';\nexport type { InfiniteData, InfiniteQueryActionCreatorResult, InfiniteQueryConfigOptions, InfiniteQueryResultSelectorResult, InfiniteQuerySubState, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './core/index';\nexport type { ApiEndpointMutation, ApiEndpointQuery, ApiEndpointInfiniteQuery, ApiModules, CoreModule, PrefetchOptions } from './core/module';\nexport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nexport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nexport type { Id as TSHelpersId, NoInfer as TSHelpersNoInfer, Override as TSHelpersOverride } from './tsHelpers';\nexport { NamedSchemaError } from './standardSchema';","import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, FullTagDescription, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFromAnyQuery, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n  _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n  queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n  requestId: string;\n  fixedCacheKey?: string;\n} | {\n  requestId?: string;\n  fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number;\n  refetchOnReconnect: boolean;\n  refetchOnFocus: boolean;\n};\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam;\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (lastPage: DataType, allPages: Array<DataType>, lastPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>;\n  pageParams: Array<PageParam>;\n};\n\n// NOTE: DO NOT import and use this for runtime comparisons internally,\n// except in the RTKQ React package. Use the string versions just below this.\n// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated\n// constants like \"initialized\":\n// https://github.com/evanw/esbuild/releases/tag/v0.14.7\n// We still have to use this in the React package since we don't publicly export\n// the string constants below.\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\n\n// Use these string constants for runtime comparisons internally\nexport const STATUS_UNINITIALIZED = QueryStatus.uninitialized;\nexport const STATUS_PENDING = QueryStatus.pending;\nexport const STATUS_FULFILLED = QueryStatus.fulfilled;\nexport const STATUS_REJECTED = QueryStatus.rejected;\nexport type RequestStatusFlags = {\n  status: QueryStatus.uninitialized;\n  isUninitialized: true;\n  isLoading: false;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.pending;\n  isUninitialized: false;\n  isLoading: true;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.fulfilled;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: true;\n  isError: false;\n} | {\n  status: QueryStatus.rejected;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: false;\n  isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === STATUS_UNINITIALIZED,\n    isLoading: status === STATUS_PENDING,\n    isSuccess: status === STATUS_FULFILLED,\n    isError: status === STATUS_REJECTED\n  } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\nexport type SubscribersInternal = Map<string, SubscriptionOptions>;\nexport type Subscribers = {\n  [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>;\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string;\n  /**\n   * The received data from the query\n   */\n  data?: DataType;\n  /**\n   * The received error if applicable\n   */\n  error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string;\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number;\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n  error: undefined;\n}) | ({\n  status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n  status: QueryStatus.uninitialized;\n  originalArgs?: undefined;\n  data?: undefined;\n  error?: undefined;\n  requestId?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n  direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = {\n  requestId: string;\n  data?: ResultTypeFrom<D>;\n  error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  endpointName: string;\n  startedTimeStamp: number;\n  fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = (({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n  error: undefined;\n}) | (({\n  status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n  data?: undefined;\n}) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n  requestId?: undefined;\n  status: QueryStatus.uninitialized;\n  data?: undefined;\n  error?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n  queries: QueryState<D>;\n  mutations: MutationState<D>;\n  provided: InvalidationState<E>;\n  subscriptions: SubscriptionState;\n  config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = {\n  tags: { [_ in TagTypes]: {\n    [id: string]: Array<QueryCacheKey>;\n    [id: number]: Array<QueryCacheKey>;\n  } };\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;\n};\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionInternalState = Map<string, SubscribersInternal>;\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath;\n  online: boolean;\n  focused: boolean;\n  middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number;\n  invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from '@reduxjs/toolkit';","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n    return newObj;\n  }\n  const newKeys = Object.keys(newObj);\n  const oldKeys = Object.keys(oldObj);\n  let isSameObject = newKeys.length === oldKeys.length;\n  const mergeObj: any = Array.isArray(newObj) ? [] : {};\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n  }\n  return isSameObject ? oldObj : mergeObj;\n}","// Preserve type guard predicate behavior when passing to mapper\nexport 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[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[] {\n  return array.reduce<(U | U[])[]>((acc, item, i) => {\n    if (predicate(item as any, i)) {\n      acc.push(mapper(item as any, i));\n    }\n    return acc;\n  }, []).flat() as U[];\n}","/**\n * If either :// or // is present consider it to be an absolute url\n *\n * @param url string\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url);\n}","/**\n * Assumes true for a non-browser env, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true;\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null;\n}\nexport function filterNullishValues<T>(map?: Map<any, T>) {\n  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[];\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n  if (!base) {\n    return url!;\n  }\n  if (!url) {\n    return base;\n  }\n  if (isAbsoluteUrl(url)) {\n    return url;\n  }\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n  base = withoutTrailingSlash(base);\n  url = withoutLeadingSlash(url);\n  return `${base}${delimiter}${url}`;\n}","// Duplicate some of the utils in `/src/utils` to ensure\n// we don't end up dragging in larger chunks of the RTK core\n// into the RTKQ bundle\n\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport const createNewMap = () => new Map();","// AbortSignal.timeout() is currently baseline 2024\nexport const timeoutSignal = (milliseconds: number) => {\n  const abortController = new AbortController();\n  setTimeout(() => {\n    const message = 'signal timed out';\n    const name = 'TimeoutError';\n    abortController.abort(\n    // some environments (React Native, Node) don't have DOMException\n    typeof DOMException !== 'undefined' ? new DOMException(message, name) : Object.assign(new Error(message), {\n      name\n    }));\n  }, milliseconds);\n  return abortController.signal;\n};\n\n// AbortSignal.any() is currently baseline 2024\nexport const anySignal = (...signals: AbortSignal[]) => {\n  // if any are already aborted, return an already aborted signal\n  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);\n\n  // otherwise, create a new signal that aborts when any of the given signals abort\n  const abortController = new AbortController();\n  for (const signal of signals) {\n    signal.addEventListener('abort', () => abortController.abort(signal.reason), {\n      signal: abortController.signal,\n      once: true\n    });\n  }\n  return abortController.signal;\n};","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nimport { anySignal, timeoutSignal } from './utils/signals';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n  headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n  url: string;\n  params?: Record<string, any>;\n  body?: any;\n  responseHandler?: ResponseHandler;\n  validateStatus?: (response: Response, body: any) => boolean;\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n  /**\n   * * `number`:\n   *   HTTP status code\n   */\n  status: number;\n  data: unknown;\n} | {\n  /**\n   * * `\"FETCH_ERROR\"`:\n   *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n   **/\n  status: 'FETCH_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"PARSING_ERROR\"`:\n   *   An error happened during parsing.\n   *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n   *   or an error occurred while executing a custom `responseHandler`.\n   **/\n  status: 'PARSING_ERROR';\n  originalStatus: number;\n  data: string;\n  error: string;\n} | {\n  /**\n   * * `\"TIMEOUT_ERROR\"`:\n   *   Request timed out\n   **/\n  status: 'TIMEOUT_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"CUSTOM_ERROR\"`:\n   *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n   **/\n  status: 'CUSTOM_ERROR';\n  data?: unknown;\n  error: string;\n};\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj;\n  }\n  const copy: Record<string, any> = {\n    ...obj\n  };\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k];\n  }\n  return copy;\n}\n\n// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\nconst isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string;\n  prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n    arg: string | FetchArgs;\n    extraOptions: unknown;\n  }) => MaybePromise<Headers | void>;\n  fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n  paramsSerializer?: (params: Record<string, any>) => string;\n  /**\n   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean;\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string;\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n  request: Request;\n  response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = x => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n  }\n  return async (arg, api, extraOptions) => {\n    const {\n      getState,\n      extra,\n      endpoint,\n      forced,\n      type\n    } = api;\n    let meta: FetchBaseQueryMeta | undefined;\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? 'json' as const,\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? {\n      url: arg\n    } : arg;\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,\n      ...rest\n    };\n    headers = new Headers(stripUndefined(headers));\n    config.headers = (await prepareHeaders(headers, {\n      getState,\n      arg,\n      extra,\n      endpoint,\n      forced,\n      type,\n      extraOptions\n    })) || headers;\n    const bodyIsJsonifiable = isJsonifiable(config.body);\n\n    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically\n    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)\n    if (config.body != null && !bodyIsJsonifiable && typeof config.body !== 'string') {\n      config.headers.delete('content-type');\n    }\n    if (!config.headers.has('content-type') && bodyIsJsonifiable) {\n      config.headers.set('content-type', jsonContentType);\n    }\n    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer);\n    }\n\n    // Set Accept header based on responseHandler if not already set\n    if (!config.headers.has('accept')) {\n      if (responseHandler === 'json') {\n        config.headers.set('accept', 'application/json');\n      } else if (responseHandler === 'text') {\n        config.headers.set('accept', 'text/plain, text/html, */*');\n      }\n      // For 'content-type' responseHandler, don't set Accept (let server decide)\n    }\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?';\n      const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n      url += divider + query;\n    }\n    url = joinUrls(baseUrl, url);\n    const request = new Request(url, config);\n    const requestClone = new Request(url, config);\n    meta = {\n      request: requestClone\n    };\n    let response;\n    try {\n      response = await fetchFn(request);\n    } catch (e) {\n      return {\n        error: {\n          status: (e instanceof Error || typeof DOMException !== 'undefined' && e instanceof DOMException) && e.name === 'TimeoutError' ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n          error: String(e)\n        },\n        meta\n      };\n    }\n    const responseClone = response.clone();\n    meta.response = responseClone;\n    let resultData: any;\n    let responseText: string = '';\n    try {\n      let handleResponseError;\n      await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n      // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n      // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n      responseClone.text().then(r => responseText = r, () => {})]);\n      if (handleResponseError) throw handleResponseError;\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e)\n        },\n        meta\n      };\n    }\n    return validateStatus(response, resultData) ? {\n      data: resultData,\n      meta\n    } : {\n      error: {\n        status: response.status,\n        data: resultData\n      },\n      meta\n    };\n  };\n  async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response);\n    }\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n    }\n    if (responseHandler === 'json') {\n      const text = await response.text();\n      return text.length ? JSON.parse(text) : null;\n    }\n    return response.text();\n  }\n}","export class HandledError {\n  constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5, signal?: AbortSignal) {\n  const attempts = Math.min(attempt, maxRetries);\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n\n  await new Promise<void>((resolve, reject) => {\n    const timeoutId = setTimeout(() => resolve(), timeout);\n\n    // If signal is provided and gets aborted, clear timeout and reject\n    if (signal) {\n      const abortHandler = () => {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      };\n\n      // Check if already aborted\n      if (signal.aborted) {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      } else {\n        signal.addEventListener('abort', abortHandler, {\n          once: true\n        });\n      }\n    }\n  });\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n  attempt: number;\n  baseQueryApi: BaseQueryApi;\n  extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (attempt: number, maxRetries: number, signal?: AbortSignal) => Promise<void>;\n} & ({\n  /**\n   * How many times the query will be retried (default: 5)\n   */\n  maxRetries?: number;\n  retryCondition?: undefined;\n} | {\n  /**\n   * Callback to determine if a retry should be attempted.\n   * Return `true` for another retry and `false` to quit trying prematurely.\n   */\n  retryCondition?: RetryConditionFunction;\n  maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n  throw Object.assign(new HandledError({\n    error,\n    meta\n  }), {\n    throwImmediately: true\n  });\n}\n\n/**\n * Checks if the abort signal is aborted and fails immediately if so.\n * Used to exit retry loops cleanly when a request is aborted.\n */\nfunction failIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    fail({\n      status: 'CUSTOM_ERROR',\n      error: 'Aborted'\n    });\n  }\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n  const [maxRetries] = possibleMaxRetries.slice(-1);\n  const defaultRetryCondition: RetryConditionFunction = (_, __, {\n    attempt\n  }) => attempt <= maxRetries;\n  const options: {\n    maxRetries: number;\n    backoff: typeof defaultBackoff;\n    retryCondition: typeof defaultRetryCondition;\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions\n  };\n  let retry = 0;\n  while (true) {\n    // Check if aborted before each attempt\n    failIfAborted(api.signal);\n    try {\n      const result = await baseQuery(args, api, extraOptions);\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result);\n      }\n      return result;\n    } catch (e: any) {\n      retry++;\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value;\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e;\n      }\n      if (e instanceof HandledError) {\n        if (!options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n          attempt: retry,\n          baseQueryApi: api,\n          extraOptions\n        })) {\n          return e.value; // Max retries for expected error\n        }\n      } else {\n        // For unexpected errors, respect maxRetries\n        if (retry > options.maxRetries) {\n          // Return the error as a proper error response instead of throwing\n          return {\n            error: e\n          };\n        }\n      }\n\n      // Check if aborted before backoff\n      failIfAborted(api.signal);\n      try {\n        await options.backoff(retry, options.maxRetries, api.signal);\n      } catch (backoffError) {\n        // If backoff was aborted, exit the retry loop\n        failIfAborted(api.signal);\n        // Otherwise, rethrow the backoff error\n        throw backoffError;\n      }\n    }\n  }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n  fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const INTERNAL_PREFIX = '__rtkq/';\nconst ONLINE = 'online';\nconst OFFLINE = 'offline';\nconst FOCUS = 'focus';\nconst FOCUSED = 'focused';\nconst VISIBILITYCHANGE = 'visibilitychange';\nexport const onFocus = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${FOCUSED}`);\nexport const onFocusLost = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);\nexport const onOnline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${ONLINE}`);\nexport const onOffline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${OFFLINE}`);\nconst actions = {\n  onFocus,\n  onFocusLost,\n  onOnline,\n  onOffline\n};\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n}) => () => void) {\n  function defaultHandler() {\n    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map(action => () => dispatch(action()));\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus();\n      } else {\n        handleFocusLost();\n      }\n    };\n    let unsubscribe = () => {\n      initialized = false;\n    };\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        const handlers = {\n          [FOCUS]: handleFocus,\n          [VISIBILITYCHANGE]: handleVisibilityChange,\n          [ONLINE]: handleOnline,\n          [OFFLINE]: handleOffline\n        };\n        function updateListeners(add: boolean) {\n          Object.entries(handlers).forEach(([event, handler]) => {\n            if (add) {\n              window.addEventListener(event, handler, false);\n            } else {\n              window.removeEventListener(event, handler);\n            }\n          });\n        }\n        // Handle focus events\n        updateListeners(true);\n        initialized = true;\n        unsubscribe = () => {\n          updateListeners(false);\n          initialized = false;\n        };\n      }\n    }\n    return unsubscribe;\n  }\n  return customHandler ? customHandler(dispatch, actions) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from 'immer';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { ENDPOINT_QUERY, isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { filterNullishValues } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n  [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\ntype RefetchOptions = {\n  refetchCachedPages?: boolean;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection;\n  param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>, InfiniteQueryArgFrom<D>>>, 'initialPageParam' | 'refetchCachedPages'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n  requestId: string;\n  subscriptionOptions: SubscriptionOptions | undefined;\n  abort(): void;\n  unsubscribe(): void;\n  updateSubscriptionOptions(options: SubscriptionOptions): void;\n  queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n  arg: any;\n  unwrap(): Promise<any>;\n  refetch(options?: RefetchOptions): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: QueryArgFrom<D>;\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: InfiniteQueryArgFrom<D>;\n  unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n  refetch(options?: Pick<StartInfiniteQueryActionCreatorOptions<D>, 'refetchCachedPages'>): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n  fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n  data: ResultTypeFrom<D>;\n  error?: undefined;\n} | {\n  data?: undefined;\n  error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string;\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>;\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean;\n    fixedCacheKey?: string;\n  };\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string;\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void;\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void;\n};\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context,\n  getInternalState\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  api: Api<any, EndpointDefinitions, any, any>;\n  context: ApiContext<EndpointDefinitions>;\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState;\n}) {\n  const getRunningQueries = (dispatch: Dispatch) => getInternalState(dispatch)?.runningQueries;\n  const getRunningMutations = (dispatch: Dispatch) => getInternalState(dispatch)?.runningMutations;\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions\n  } = api.internalActions;\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk\n  };\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      return getRunningQueries(dispatch)?.get(queryCacheKey) as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningMutationThunk(\n  /**\n   * this is only here to allow TS to infer the result type by input value\n   * we could use it to validate the result, but it's probably not necessary\n   */\n  _endpointName: string, fixedCacheKeyOrRequestId: string) {\n    return (dispatch: Dispatch) => {\n      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as MutationActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningQueries(dispatch));\n  }\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningMutations(dispatch));\n  }\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return;\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      (middlewareWarning as any).triggered = true;\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n        // Otherwise, must not have been added\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n      }\n    }\n  }\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n    const queryAction: AnyQueryActionCreator<any> = (arg, {\n      subscribe = true,\n      forceRefetch,\n      subscriptionOptions,\n      [forceQueryFnSymbol]: forceQueryFn,\n      ...rest\n    } = {}) => (dispatch, getState) => {\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName\n      });\n      let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n      const commonThunkArgs = {\n        ...rest,\n        type: ENDPOINT_QUERY as 'query',\n        subscribe,\n        forceRefetch: forceRefetch,\n        subscriptionOptions,\n        endpointName,\n        originalArgs: arg,\n        queryCacheKey,\n        [forceQueryFnSymbol]: forceQueryFn\n      };\n      if (isQueryDefinition(endpointDefinition)) {\n        thunk = queryThunk(commonThunkArgs);\n      } else {\n        const {\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam' | 'refetchCachedPages'>;\n        thunk = infiniteQueryThunk({\n          ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n          // Supply these even if undefined. This helps with a field existence\n          // check over in `buildSlice.ts`\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        });\n      }\n      const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n      const thunkResult = dispatch(thunk);\n      const stateAfter = selector(getState());\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort\n      } = thunkResult;\n      const skippedSynchronously = stateAfter.requestId !== requestId;\n      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);\n      const selectFromState = () => selector(getState());\n      const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n      // a query has been forced (upsertQueryData)\n      // -> we want to resolve it once data has been written with the data that will be written\n      thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n      // a query has been skipped due to a condition and we do not have any currently running query\n      // -> we want to resolve it immediately with the current data\n      Promise.resolve(stateAfter) :\n      // query just started or one is already in flight\n      // -> wait for the running query, then resolve with data from after that\n      Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n        arg,\n        requestId,\n        subscriptionOptions,\n        queryCacheKey,\n        abort,\n        async unwrap() {\n          const result = await statePromise;\n          if (result.isError) {\n            throw result.error;\n          }\n          return result.data;\n        },\n        refetch: (options?: RefetchOptions) => dispatch(queryAction(arg, {\n          subscribe: false,\n          forceRefetch: true,\n          ...options\n        })),\n        unsubscribe() {\n          if (subscribe) dispatch(unsubscribeQueryResult({\n            queryCacheKey,\n            requestId\n          }));\n        },\n        updateSubscriptionOptions(options: SubscriptionOptions) {\n          statePromise.subscriptionOptions = options;\n          dispatch(updateSubscriptionOptions({\n            endpointName,\n            requestId,\n            queryCacheKey,\n            options\n          }));\n        }\n      });\n      if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n        const runningQueries = getRunningQueries(dispatch)!;\n        runningQueries.set(queryCacheKey, statePromise);\n        statePromise.then(() => {\n          runningQueries.delete(queryCacheKey);\n        });\n      }\n      return statePromise;\n    };\n    return queryAction;\n  }\n  function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return queryAction;\n  }\n  function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return infiniteQueryAction;\n  }\n  function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n    return (arg, {\n      track = true,\n      fixedCacheKey\n    } = {}) => (dispatch, getState) => {\n      const thunk = mutationThunk({\n        type: 'mutation',\n        endpointName,\n        originalArgs: arg,\n        track,\n        fixedCacheKey\n      });\n      const thunkResult = dispatch(thunk);\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort,\n        unwrap\n      } = thunkResult;\n      const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n        data\n      })), error => ({\n        error\n      }));\n      const reset = () => {\n        dispatch(removeMutationResult({\n          requestId,\n          fixedCacheKey\n        }));\n      };\n      const ret = Object.assign(returnValuePromise, {\n        arg: thunkResult.arg,\n        requestId,\n        abort,\n        unwrap,\n        reset\n      });\n      const runningMutations = getRunningMutations(dispatch)!;\n      runningMutations.set(requestId, ret);\n      ret.then(() => {\n        runningMutations.delete(requestId);\n      });\n      if (fixedCacheKey) {\n        runningMutations.set(fixedCacheKey, ret);\n        ret.then(() => {\n          if (runningMutations.get(fixedCacheKey) === ret) {\n            runningMutations.delete(fixedCacheKey);\n          }\n        });\n      }\n      return ret;\n    };\n  }\n}","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn } from './baseQueryTypes';\nimport type { CombinedState, CoreModule, QueryKeys } from './core';\nimport type { ApiModules } from './core/module';\nimport type { CreateApiOptions } from './createApi';\nimport type { EndpointBuilder, EndpointDefinition, EndpointDefinitions, UpdateDefinitions } from './endpointDefinitions';\nimport type { NoInfer, UnionToIntersection, WithRequiredProp } from './tsHelpers';\nexport type ModuleName = keyof ApiModules<any, any, any, any>;\nexport type Module<Name extends ModuleName> = {\n  name: Name;\n  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>): {\n    injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;\n  };\n};\nexport interface ApiContext<Definitions extends EndpointDefinitions> {\n  apiUid: string;\n  endpointDefinitions: Definitions;\n  batch(cb: () => void): void;\n  extractRehydrationInfo: (action: UnknownAction) => CombinedState<any, any, any> | undefined;\n  hasRehydrationInfo: (action: UnknownAction) => boolean;\n}\nexport const getEndpointDefinition = <Definitions extends EndpointDefinitions, EndpointName extends keyof Definitions>(context: ApiContext<Definitions>, endpointName: EndpointName) => context.endpointDefinitions[endpointName];\nexport 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]> & {\n  /**\n   * 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.\n   */\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\n    endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;\n    /**\n     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n     *\n     * If set to `true`, will override existing endpoints with the new definition.\n     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n     */\n    overrideExisting?: boolean | 'throw';\n  }): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;\n  /**\n   *A function to enhance a generated API with additional information. Useful with code-generation.\n   */\n  enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {\n    addTagTypes?: readonly NewTagTypes[];\n    endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? { [K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void) } : never;\n  }): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;\n};","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { SchemaError } from '@standard-schema/utils';\nimport type { SchemaType } from './endpointDefinitions';\nexport class NamedSchemaError extends SchemaError {\n  constructor(issues: readonly StandardSchemaV1.Issue[], public readonly value: any, public readonly schemaName: `${SchemaType}Schema`, public readonly _bqMeta: any) {\n    super(issues);\n  }\n}\nexport const shouldSkip = (skipSchemaValidation: boolean | SchemaType[] | undefined, schemaName: SchemaType) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(schema: Schema, data: unknown, schemaName: `${SchemaType}Schema`, bqMeta: any): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data);\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);\n  }\n  return result.value;\n}","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from '../utils/immerImports';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultDescription, ResultTypeFrom, SchemaFailureConverter, SchemaFailureHandler, SchemaFailureInfo, SchemaType } from '../endpointDefinitions';\nimport { calculateProvidedBy, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nimport { parseWithSchema, NamedSchemaError, shouldSkip } from '../standardSchema';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>;\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n  type: 'query';\n  originalArgs: unknown;\n  endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n  type: `query`;\n  originalArgs: unknown;\n  endpointName: string;\n  param: unknown;\n  direction?: InfiniteQueryDirection;\n  refetchCachedPages?: boolean;\n};\ntype MutationThunkArg = {\n  type: 'mutation';\n  originalArgs: unknown;\n  endpointName: string;\n  track?: boolean;\n  fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n  pendingMeta: {\n    startedTimeStamp: number;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  fulfilledMeta: {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  rejectedMeta: {\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;\nexport type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;\nexport type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;\nexport type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;\nexport type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[];\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[];\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n  [SHOULD_AUTOBATCH]: true;\n} => {\n  return {\n    ...arg,\n    [SHOULD_AUTOBATCH]: true\n  };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n  reducerPath,\n  baseQuery,\n  context: {\n    endpointDefinitions\n  },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation\n}: {\n  baseQuery: BaseQuery;\n  reducerPath: ReducerPath;\n  context: ApiContext<Definitions>;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  api: Api<BaseQuery, Definitions, ReducerPath, any>;\n  assertTagType: AssertTagTypes;\n  selectors: AllSelectors;\n  onSchemaFailure: SchemaFailureHandler | undefined;\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined;\n  skipSchemaValidation: boolean | SchemaType[] | undefined;\n}) {\n  type State = RootState<any, string, ReducerPath>;\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n    const endpointDefinition = endpointDefinitions[endpointName];\n    const queryCacheKey = serializeQueryArgs({\n      queryArgs: arg,\n      endpointDefinition,\n      endpointName\n    });\n    dispatch(api.internalActions.queryResultPatched({\n      queryCacheKey,\n      patches\n    }));\n    if (!updateProvided) {\n      return;\n    }\n    const newValue = api.endpoints[endpointName].select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n    dispatch(api.internalActions.updateProvidedBy([{\n      queryCacheKey,\n      providedTags\n    }]));\n  };\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items];\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n  }\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item];\n    return max && newItems.length > max ? newItems.slice(1) : newItems;\n  }\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n    const endpointDefinition = api.endpoints[endpointName];\n    const currentState = endpointDefinition.select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const ret: PatchCollection = {\n      patches: [],\n      inversePatches: [],\n      undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n    };\n    if (currentState.status === STATUS_UNINITIALIZED) {\n      return ret;\n    }\n    let newValue;\n    if ('data' in currentState) {\n      if (isDraftable(currentState.data)) {\n        const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n        ret.patches.push(...patches);\n        ret.inversePatches.push(...inversePatches);\n        newValue = value;\n      } else {\n        newValue = updateRecipe(currentState.data);\n        ret.patches.push({\n          op: 'replace',\n          path: [],\n          value: newValue\n        });\n        ret.inversePatches.push({\n          op: 'replace',\n          path: [],\n          value: currentState.data\n        });\n      }\n    }\n    if (ret.patches.length === 0) {\n      return ret;\n    }\n    dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n    return ret;\n  };\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n    type EndpointName = typeof endpointName;\n    const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n      subscribe: false,\n      forceRefetch: true,\n      [forceQueryFnSymbol]: () => ({\n        data: value\n      })\n    })) as UpsertThunkResult<Definitions, EndpointName>;\n    return res;\n  };\n  const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n  };\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }> = async (arg, {\n    signal,\n    abort,\n    rejectWithValue,\n    fulfillWithValue,\n    dispatch,\n    getState,\n    extra\n  }) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName];\n    const {\n      metaSchema,\n      skipSchemaValidation = globalSkipSchemaValidation\n    } = endpointDefinition;\n    const isQuery = arg.type === ENDPOINT_QUERY;\n    try {\n      let transformResponse: TransformCallback = defaultTransformResponse;\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n      };\n      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined;\n      let finalQueryReturnValue: QueryReturnValue;\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({\n            data\n          });\n        }\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param\n        };\n        const pageResponse = await executeRequest(finalQueryArg);\n        const addTo = previous ? addToStart : addToEnd;\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages)\n          },\n          meta: pageResponse.meta\n        };\n      };\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n        let result: QueryReturnValue;\n        const {\n          extraOptions,\n          argSchema,\n          rawResponseSchema,\n          responseSchema\n        } = endpointDefinition;\n        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {\n          finalQueryArg = await parseWithSchema(argSchema, finalQueryArg, 'argSchema', {} // we don't have a meta yet, so we can't pass it\n          );\n        }\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn();\n        } else if (endpointDefinition.query) {\n          // We should only run `transformResponse` when the endpoint has a `query` method,\n          // and we're not doing an `upsertQueryData`.\n          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n          result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n        } else {\n          result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n          let err: undefined | string;\n          if (!result) {\n            err = `${what} did not return anything.`;\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`;\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`;\n                break;\n              }\n            }\n          }\n          if (err) {\n            console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`, result);\n          }\n        }\n        if (result.error) throw new HandledError(result.error, result.meta);\n        let {\n          data\n        } = result;\n        if (rawResponseSchema && !shouldSkip(skipSchemaValidation, 'rawResponse')) {\n          data = await parseWithSchema(rawResponseSchema, result.data, 'rawResponseSchema', result.meta);\n        }\n        let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);\n        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {\n          transformedResponse = await parseWithSchema(responseSchema, transformedResponse, 'responseSchema', result.meta);\n        }\n        return {\n          ...result,\n          data: transformedResponse\n        };\n      }\n      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const {\n          infiniteQueryOptions\n        } = endpointDefinition;\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const {\n          maxPages = Infinity\n        } = infiniteQueryOptions;\n\n        // Priority: per-call override > endpoint config > default (true)\n        const refetchCachedPages = (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;\n        let result: QueryReturnValue;\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = {\n          pages: [],\n          pageParams: []\n        };\n        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch =\n        // arg.forceRefetch\n        isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n        const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward';\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n          const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);\n          result = await fetchPage(existingData, param, maxPages, previous);\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const {\n            initialPageParam = infiniteQueryOptions.initialPageParam\n          } = arg as InfiniteQueryThunkArg<any>;\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? [];\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n          const totalPages = cachedPageParams.length;\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages);\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n            } as QueryReturnValue;\n          }\n          if (refetchCachedPages) {\n            // Fetch remaining pages\n            for (let i = 1; i < totalPages; i++) {\n              const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>, arg.originalArgs);\n              result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n            }\n          }\n        }\n        finalQueryReturnValue = result;\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs);\n      }\n      if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta') && finalQueryReturnValue.meta) {\n        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, 'metaSchema', finalQueryReturnValue.meta);\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n        fulfilledTimeStamp: Date.now(),\n        baseQueryMeta: finalQueryReturnValue.meta\n      }));\n    } catch (error) {\n      let caughtError = error;\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n        const {\n          rawErrorResponseSchema,\n          errorResponseSchema\n        } = endpointDefinition;\n        let {\n          value,\n          meta\n        } = caughtError;\n        try {\n          if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, 'rawErrorResponse')) {\n            value = await parseWithSchema(rawErrorResponseSchema, value, 'rawErrorResponseSchema', meta);\n          }\n          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta);\n          }\n          let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);\n          if (errorResponseSchema && !shouldSkip(skipSchemaValidation, 'errorResponse')) {\n            transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, 'errorResponseSchema', meta);\n          }\n          return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({\n            baseQueryMeta: meta\n          }));\n        } catch (e) {\n          caughtError = e;\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n          };\n          endpointDefinition.onSchemaFailure?.(caughtError, info);\n          onSchemaFailure?.(caughtError, info);\n          const {\n            catchSchemaFailure = globalCatchSchemaFailure\n          } = endpointDefinition;\n          if (catchSchemaFailure) {\n            return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({\n              baseQueryMeta: caughtError._bqMeta\n            }));\n          }\n        }\n      } catch (e) {\n        caughtError = e;\n      }\n      if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n        console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, caughtError);\n      } else {\n        console.error(caughtError);\n      }\n      throw caughtError;\n    }\n  };\n  function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n    const fulfilledVal = requestState?.fulfilledTimeStamp;\n    const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n    }\n    return false;\n  }\n  const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n    const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n      state: RootState<any, string, ReducerPath>;\n    }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({\n        arg\n      }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName];\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n            direction: (arg as InfiniteQueryThunkArg<any>).direction\n          } : {})\n        });\n      },\n      condition(queryThunkArg, {\n        getState\n      }) {\n        const state = getState();\n        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n        const fulfilledVal = requestState?.fulfilledTimeStamp;\n        const currentArg = queryThunkArg.originalArgs;\n        const previousArg = requestState?.originalArgs;\n        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true;\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false;\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true;\n        }\n        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n          currentArg,\n          previousArg,\n          endpointState: requestState,\n          state\n        })) {\n          return true;\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false;\n        }\n        return true;\n      },\n      dispatchConditionRejection: true\n    });\n    return generatedQueryThunk;\n  };\n  const queryThunk = createQueryThunk<QueryThunkArg>();\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n  const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({\n        startedTimeStamp: Date.now()\n      });\n    }\n  });\n  const hasTheForce = (options: any): options is {\n    force: boolean;\n  } => 'force' in options;\n  const hasMaxAge = (options: any): options is {\n    ifOlderThan: false | number;\n  } => 'ifOlderThan' in options;\n  const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions = {}): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n    const force = hasTheForce(options) && options.force;\n    const maxAge = hasMaxAge(options) && options.ifOlderThan;\n    const queryAction = (force: boolean = true) => {\n      const options: StartQueryActionCreatorOptions = {\n        forceRefetch: force,\n        subscribe: false\n      };\n      return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n    };\n    const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n    if (force) {\n      dispatch(queryAction());\n    } else if (maxAge) {\n      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n      if (!lastFulfilledTs) {\n        dispatch(queryAction());\n        return;\n      }\n      const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n      if (shouldRetrigger) {\n        dispatch(queryAction());\n      }\n    } else {\n      // If prefetching with no options, just let it try\n      dispatch(queryAction(false));\n    }\n  };\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n  }\n  function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n    } as Matchers<Thunk, any>;\n  }\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions\n  };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  const lastIndex = pages.length - 1;\n  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n  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);\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../utils/immerImports';\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}","import type { PayloadAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { STATUS_FULFILLED, STATUS_PENDING, QueryStatus, STATUS_REJECTED, STATUS_UNINITIALIZED } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { ENDPOINT_QUERY, isInfiniteQueryDefinition, type AssertTagTypes, type EndpointDefinitions, type FullTagDescription, type QueryDefinition } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { applyPatches, original, isDraft } from '../utils/immerImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport { getCurrent } from '../utils/getCurrent';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n  endpointName: EndpointName;\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string;\n  arg: unknown;\n  value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg;\n  value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n  const substate = state[queryCacheKey];\n  if (substate) {\n    update(substate);\n  }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n} | MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}, update: (substate: MutationSubState<any>) => void) {\n  const substate = state[getMutationCacheKey(id)];\n  if (substate) {\n    update(substate);\n  }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo\n  },\n  assertTagType,\n  config\n}: {\n  reducerPath: string;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  context: ApiContext<EndpointDefinitions>;\n  assertTagType: AssertTagTypes;\n  config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`);\n  function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n    // requestStatus: 'pending'\n  } & {\n    startedTimeStamp: number;\n  }) {\n    draft[arg.queryCacheKey] ??= {\n      status: STATUS_UNINITIALIZED,\n      endpointName: arg.endpointName\n    };\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n      substate.status = STATUS_PENDING;\n      substate.requestId = upserting && substate.requestId ?\n      // for `upsertQuery` **updates**, keep the current `requestId`\n      substate.requestId :\n      // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n      meta.requestId;\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs;\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp;\n      const endpointDefinition = definitions[meta.arg.endpointName];\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;\n        (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n      }\n    });\n  }\n  function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n  } & {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n  }, payload: unknown, upserting: boolean) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n      if (substate.requestId !== meta.requestId && !upserting) return;\n      const {\n        merge\n      } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n      substate.status = STATUS_FULFILLED;\n      if (merge) {\n        if (substate.data !== undefined) {\n          const {\n            fulfilledTimeStamp,\n            arg,\n            baseQueryMeta,\n            requestId\n          } = meta;\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, draftSubstateData => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId\n            });\n          });\n          substate.data = newData;\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload;\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n      }\n      delete substate.error;\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n    });\n  }\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey\n          }\n        }: PayloadAction<QuerySubstateIdentifier>) {\n          delete draft[queryCacheKey];\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n      },\n      cacheEntriesUpserted: {\n        reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n          RTK_autoBatch: boolean;\n          requestId: string;\n          timestamp: number;\n        }>) {\n          for (const entry of action.payload) {\n            const {\n              queryDescription: arg,\n              value\n            } = entry;\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp\n            });\n            writeFulfilledCacheEntry(draft, {\n              arg,\n              requestId: action.meta.requestId,\n              fulfilledTimeStamp: action.meta.timestamp,\n              baseQueryMeta: {}\n            }, value,\n            // We know we're upserting here\n            true);\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n            const {\n              endpointName,\n              arg,\n              value\n            } = entry;\n            const endpointDefinition = definitions[endpointName];\n            const queryDescription: QueryThunkArg = {\n              type: ENDPOINT_QUERY as 'query',\n              endpointName,\n              originalArgs: entry.arg,\n              queryCacheKey: serializeQueryArgs({\n                queryArgs: arg,\n                endpointDefinition,\n                endpointName\n              })\n            };\n            return {\n              queryDescription,\n              value\n            };\n          });\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now()\n            }\n          };\n          return result;\n        }\n      },\n      queryResultPatched: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey,\n            patches\n          }\n        }: PayloadAction<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n            substate.data = applyPatches(substate.data as any, patches.concat());\n          });\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(queryThunk.pending, (draft, {\n        meta,\n        meta: {\n          arg\n        }\n      }) => {\n        const upserting = isUpsertQuery(arg);\n        writePendingCacheEntry(draft, arg, upserting, meta);\n      }).addCase(queryThunk.fulfilled, (draft, {\n        meta,\n        payload\n      }) => {\n        const upserting = isUpsertQuery(meta.arg);\n        writeFulfilledCacheEntry(draft, meta, payload, upserting);\n      }).addCase(queryThunk.rejected, (draft, {\n        meta: {\n          condition,\n          arg,\n          requestId\n        },\n        error,\n        payload\n      }) => {\n        updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n          if (condition) {\n            // request was aborted due to condition (another query already running)\n          } else {\n            // request failed\n            if (substate.requestId !== requestId) return;\n            substate.status = STATUS_REJECTED;\n            substate.error = (payload ?? error) as any;\n          }\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          queries\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(queries)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, {\n          payload\n        }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload);\n          if (cacheKey in draft) {\n            delete draft[cacheKey];\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(mutationThunk.pending, (draft, {\n        meta,\n        meta: {\n          requestId,\n          arg,\n          startedTimeStamp\n        }\n      }) => {\n        if (!arg.track) return;\n        draft[getMutationCacheKey(meta)] = {\n          requestId,\n          status: STATUS_PENDING,\n          endpointName: arg.endpointName,\n          startedTimeStamp\n        };\n      }).addCase(mutationThunk.fulfilled, (draft, {\n        payload,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_FULFILLED;\n          substate.data = payload;\n          substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n        });\n      }).addCase(mutationThunk.rejected, (draft, {\n        payload,\n        error,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_REJECTED;\n          substate.error = (payload ?? error) as any;\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          mutations\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(mutations)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) &&\n          // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n          key !== entry?.requestId) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  type CalculateProvidedByAction = UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>;\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {}\n  };\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(draft, action: PayloadAction<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>) {\n          for (const {\n            queryCacheKey,\n            providedTags\n          } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey);\n            for (const {\n              type,\n              id\n            } of providedTags) {\n              const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] = providedTags as FullTagDescription<string>[];\n          }\n        },\n        prepare: prepareAutoBatched<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n        payload: {\n          queryCacheKey\n        }\n      }) => {\n        removeCacheKeyFromTags(draft, queryCacheKey);\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          provided\n        } = extractRehydrationInfo(action)!;\n        for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {\n          for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n            const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n            for (const queryCacheKey of cacheKeys) {\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n              draft.keys[queryCacheKey] = provided.keys[queryCacheKey];\n            }\n          }\n        }\n      }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n        writeProvidedTagsForQueries(draft, [action]);\n      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {\n        const mockActions: CalculateProvidedByAction[] = action.payload.map(({\n          queryDescription,\n          value\n        }) => {\n          return {\n            type: 'UNKNOWN',\n            payload: value,\n            meta: {\n              requestStatus: 'fulfilled',\n              requestId: 'UNKNOWN',\n              arg: queryDescription\n            }\n          };\n        });\n        writeProvidedTagsForQueries(draft, mockActions);\n      });\n    }\n  });\n  function removeCacheKeyFromTags(draft: InvalidationState<any>, queryCacheKey: QueryCacheKey) {\n    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type;\n      const tagId = tag.id ?? '__internal_without_id';\n      const tagSubscriptions = draft.tags[tagType]?.[tagId];\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(qc => qc !== queryCacheKey);\n      }\n    }\n    delete draft.keys[queryCacheKey];\n  }\n  function writeProvidedTagsForQueries(draft: InvalidationState<string>, actions: CalculateProvidedByAction[]) {\n    const providedByEntries = actions.map(action => {\n      const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n      const {\n        queryCacheKey\n      } = action.meta.arg;\n      return {\n        queryCacheKey,\n        providedTags\n      };\n    });\n    invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(d, a: PayloadAction<{\n        endpointName: string;\n        requestId: string;\n        options: Subscribers[number];\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      unsubscribeQueryResult(d, a: PayloadAction<{\n        requestId: string;\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {}\n    }\n  });\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload);\n        },\n        prepare: prepareAutoBatched<Patch[]>()\n      }\n    }\n  });\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, {\n        payload\n      }: PayloadAction<string>) {\n        state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n      }\n    },\n    extraReducers: builder => {\n      builder.addCase(onOnline, state => {\n        state.online = true;\n      }).addCase(onOffline, state => {\n        state.online = false;\n      }).addCase(onFocus, state => {\n        state.focused = true;\n      }).addCase(onFocusLost, state => {\n        state.focused = false;\n      })\n      // update the state to be a new object to be picked up as a \"state change\"\n      // by redux-persist's `autoMergeLevel2`\n      .addMatcher(hasRehydrationInfo, draft => ({\n        ...draft\n      }));\n    }\n  });\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer\n  });\n  const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState\n  };\n  return {\n    reducer,\n    actions\n  };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { filterMap, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState, QueryStatus } from './apiState';\nimport { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { type AllQueryKeys, getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n  isFetchNextPageError: boolean;\n  isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n  requestId: string | undefined;\n  fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n  status: STATUS_UNINITIALIZED\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  reducerPath: ReducerPath;\n  createSelector: typeof _createSelector;\n}) {\n  type RootState = _RootState<Definitions, string, string>;\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig\n  };\n  function withRequestFlags<T extends {\n    status: QueryStatus;\n  }>(substate: T): T & RequestStatusFlags {\n    return {\n      ...substate,\n      ...getRequestStatusFlags(substate.status)\n    };\n  }\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath];\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state;\n        (selectApiState as any).triggered = true;\n        console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n      }\n    }\n    return state;\n  }\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries;\n  }\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey];\n  }\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations;\n  }\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config;\n  }\n  function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n    status: QueryStatus;\n  }>(substate: T) => T & RequestStatusFlags) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner);\n      }\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n      return createSelector(selectQuerySubstate, combiner);\n    };\n  }\n  function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n  }\n  function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const {\n      infiniteQueryOptions\n    } = endpointDefinition;\n    function withInfiniteQueryResultFlags<T extends {\n      status: QueryStatus;\n    }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status)\n      };\n      const {\n        isLoading,\n        isError,\n        direction\n      } = stateWithRequestFlags;\n      const isForward = direction === 'forward';\n      const isBackward = direction === 'backward';\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward\n      };\n    }\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n  }\n  function buildMutationSelector() {\n    return (id => {\n      let mutationId: string | typeof skipToken;\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken;\n      } else {\n        mutationId = id;\n      }\n      const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n      return createSelector(finalSelectMutationSubstate, withRequestFlags);\n    }) as MutationResultSelectorFactory<any, RootState>;\n  }\n  function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n    endpointName: string;\n    originalArgs: any;\n    queryCacheKey: QueryCacheKey;\n  }> {\n    const apiState = state[reducerPath];\n    const toInvalidate = new Set<QueryCacheKey>();\n    const finalTags = filterMap(tags, isNotNullish, expandTagDescription);\n    for (const tag of finalTags) {\n      const provided = apiState.provided.tags[tag.type];\n      if (!provided) {\n        continue;\n      }\n      let invalidateSubscriptions = (tag.id !== undefined ?\n      // id given: invalidate all queries that provide this type & id\n      provided[tag.id] :\n      // no id: invalidate all queries that provide this type\n      Object.values(provided).flat()) ?? [];\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate);\n      }\n    }\n    return Array.from(toInvalidate.values()).flatMap(queryCacheKey => {\n      const querySubState = apiState.queries[queryCacheKey];\n      return querySubState ? {\n        queryCacheKey,\n        endpointName: querySubState.endpointName!,\n        originalArgs: querySubState.originalArgs\n      } : [];\n    });\n  }\n  function selectCachedArgsForQuery<QueryName extends AllQueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return filterMap(Object.values(selectQueries(state) as QueryState<any>), (entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n      status: QueryStatus.uninitialized;\n    }> => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, entry => entry.originalArgs);\n  }\n  function getHasNextPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data) return false;\n    return getNextPageParam(options, data, queryArg) != null;\n  }\n  function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data || !options.getPreviousPageParam) return false;\n    return getPreviousPageParam(options, data, queryArg) != null;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport { getEndpointDefinition, type Api, type ApiContext, type Module, type ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions, SchemaFailureConverter, SchemaFailureHandler, SchemaType } from './endpointDefinitions';\nimport { DefinitionType, ENDPOINT_INFINITEQUERY, ENDPOINT_MUTATION, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n  /**\n   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery;\n  /**\n   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[];\n  /**\n   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath;\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>;\n  /**\n   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n   */\n  endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n  /**\n   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts'\n   *     })\n   *   }),\n   *   // highlight-start\n   *   keepUnusedDataFor: 5\n   *   // highlight-end\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately';\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (action: UnknownAction, {\n    reducerPath\n  }: {\n    reducerPath: ReducerPath;\n  }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n      reducerPath: (options.reducerPath ?? 'api') as any\n    }));\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n          finalSerializeQueryArgs = queryArgsApi => {\n            const initialResult = endpointSQA(queryArgsApi);\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult;\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult\n              });\n            }\n          };\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs;\n        }\n        return finalSerializeQueryArgs(queryArgsApi);\n      },\n      tagTypes: [...(options.tagTypes || [])]\n    };\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn();\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n    };\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({\n        addTagTypes,\n        endpoints\n      }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;\n              (optionsWithDefaults.tagTypes as any[]).push(eT);\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(getEndpointDefinition(context, endpointName));\n            } else {\n              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);\n            }\n          }\n        }\n        return api;\n      }\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n    const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n    function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: x => ({\n          ...x,\n          type: ENDPOINT_QUERY\n        }) as any,\n        mutation: x => ({\n          ...x,\n          type: ENDPOINT_MUTATION\n        }) as any,\n        infiniteQuery: x => ({\n          ...x,\n          type: ENDPOINT_INFINITEQUERY\n        }) as any\n      });\n      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n            console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          }\n          continue;\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          if (isInfiniteQueryDefinition(definition)) {\n            const {\n              infiniteQueryOptions\n            } = definition;\n            const {\n              maxPages,\n              getPreviousPageParam\n            } = infiniteQueryOptions;\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n              }\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n              }\n            }\n          }\n        }\n        context.endpointDefinitions[endpointName] = definition;\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition);\n        }\n      }\n      return api as any;\n    }\n    return api.injectEndpoints({\n      endpoints: options.endpoints as any\n    });\n  };\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs\n}) => {\n  let serialized = '';\n  const cached = cache?.get(queryArgs);\n  if (typeof cached === 'string') {\n    serialized = cached;\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? {\n        $bigint: value.toString()\n      } : value;\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n        acc[key] = (value as any)[key];\n        return acc;\n      }, {}) : value;\n      return value;\n    });\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified);\n    }\n    serialized = stringified;\n  }\n  return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n  return function () {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n  };\n}","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionInternalState, SubscriptionState } from '../apiState';\nimport { produceWithPatches } from '../../utils/immerImports';\nimport type { Action } from '@reduxjs/toolkit';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n  api,\n  queryThunk,\n  internalState,\n  mwApi\n}) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n  let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n  const {\n    updateSubscriptionOptions,\n    unsubscribeQueryResult\n  } = api.internalActions;\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (currentSubscriptions: SubscriptionInternalState, action: Action) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const {\n        queryCacheKey,\n        requestId,\n        options\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub?.has(requestId)) {\n        sub.set(requestId, options);\n      }\n      return true;\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const {\n        queryCacheKey,\n        requestId\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub) {\n        sub.delete(requestId);\n      }\n      return true;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      currentSubscriptions.delete(action.payload.queryCacheKey);\n      return true;\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: {\n          arg,\n          requestId\n        }\n      } = action;\n      const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n      if (arg.subscribe) {\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n      }\n      return true;\n    }\n    let mutated = false;\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: {\n          condition,\n          arg,\n          requestId\n        }\n      } = action;\n      if (condition && arg.subscribe) {\n        const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n        mutated = true;\n      }\n    }\n    return mutated;\n  };\n  const getSubscriptions = () => internalState.currentSubscriptions;\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions();\n    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);\n    return subscriptionsForQueryArg?.size ?? 0;\n  };\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions();\n    return !!subscriptions?.get(queryCacheKey)?.get(requestId);\n  };\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed\n  };\n  function serializeSubscriptions(currentSubscriptions: SubscriptionInternalState): SubscriptionState {\n    // We now use nested Maps for subscriptions, instead of\n    // plain Records. Stringify this accordingly so we can\n    // convert it to the shape we need for the store.\n    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));\n  }\n  return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);\n    }\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = {};\n      internalState.currentSubscriptions.clear();\n      updateSyncTimer = null;\n      return [true, false];\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors];\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n    let actionShouldContinue = true;\n\n    // HACK Sneak the test-only polling state back out\n    if (process.env.NODE_ENV === 'test' && typeof action.type === 'string' && action.type === `${api.reducerPath}/getPolling`) {\n      return [false, internalState.currentPolls] as any;\n    }\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = serializeSubscriptions(internalState.currentSubscriptions);\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions;\n          updateSyncTimer = null;\n        }, 500);\n      }\n      const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n    }\n    return [actionShouldContinue, false];\n  };\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\n\n/**\n * @example\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => 'posts',\n *       // highlight-start\n *       keepUnusedDataFor: 5\n *       // highlight-end\n *     })\n *   })\n * })\n * ```\n */\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   */\n  keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectConfig\n  },\n  getRunningQueryThunk,\n  mwApi\n}) => {\n  const {\n    removeQueryResult,\n    unsubscribeQueryResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);\n    if (!subscriptions) {\n      return false;\n    }\n    const hasSubscriptions = subscriptions.size > 0;\n    return hasSubscriptions;\n  }\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n  function abortAllPromises<T extends {\n    abort?: () => void;\n  }>(promiseMap: Map<string, T | undefined>): void {\n    for (const promise of promiseMap.values()) {\n      promise?.abort?.();\n    }\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    const state = mwApi.getState();\n    const config = selectConfig(state);\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[];\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n      } else {\n        const {\n          queryCacheKey\n        } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n        queryCacheKeys = [queryCacheKey];\n      }\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n    }\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout);\n        delete currentRemovalTimeouts[key];\n      }\n      abortAllPromises(internalState.runningQueries);\n      abortAllPromises(internalState.runningMutations);\n    }\n    if (context.hasRehydrationInfo(action)) {\n      const {\n        queries\n      } = context.extractRehydrationInfo(action)!;\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n    }\n  };\n  function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n    const state = api.getState();\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey);\n      if (entry?.endpointName) {\n        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config);\n      }\n    }\n  }\n  function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string, api: SubMiddlewareApi, config: ConfigState<string>) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName) as QueryDefinition<any, any, any, any>;\n    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return;\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n      if (currentTimeout) {\n        clearTimeout(currentTimeout);\n      }\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          // Try to abort any running query for this cache key\n          const entry = selectQueryEntry(api.getState(), queryCacheKey);\n          if (entry?.endpointName) {\n            const runningQuery = api.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));\n            runningQuery?.abort();\n          }\n          api.dispatch(removeQueryResult({\n            queryCacheKey\n          }));\n        }\n        delete currentRemovalTimeouts![queryCacheKey];\n      }, finalKeepUnusedDataFor * 1000);\n    }\n  }\n  return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta, BaseQueryResult } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition, DefinitionType } from '../../endpointDefinitions';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nimport { getEndpointDefinition } from '@internal/query/apiTypes';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<{\n    type: DefinitionType.query;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<{\n    type: DefinitionType.mutation;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>;\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>;\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown;\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: MetaType;\n  }, typeof neverResolvedError>;\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectApiState\n  }\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk);\n  const isMutationThunk = isAsyncThunkAction(mutationThunk);\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    valueResolved?(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    cacheEntryRemoved(): void;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const {\n    removeQueryResult,\n    removeMutationResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta\n      });\n      delete lifecycle.valueResolved;\n    }\n  }\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey];\n      lifecycle.cacheEntryRemoved();\n    }\n  }\n  function getActionMetaFields(action: ReturnType<typeof queryThunk.pending> | ReturnType<typeof mutationThunk.pending>) {\n    const {\n      arg,\n      requestId\n    } = action.meta;\n    const {\n      endpointName,\n      originalArgs\n    } = arg;\n    return [endpointName, originalArgs, requestId] as const;\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey;\n    function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    }\n    if (queryThunk.pending.match(action)) {\n      const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);\n    } else if (cacheEntriesUpserted.match(action)) {\n      for (const {\n        queryDescription,\n        value\n      } of action.payload) {\n        const {\n          endpointName,\n          originalArgs,\n          queryCacheKey\n        } = queryDescription;\n        checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n        resolveLifecycleEntry(queryCacheKey, value, {});\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n      if (state) {\n        const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n    } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {\n      removeLifecycleEntry(cacheKey);\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey);\n      }\n    }\n  };\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n    }\n    if (removeQueryResult.match(action)) return action.payload.queryCacheKey;\n    if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n    return '';\n  }\n  function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName);\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n    if (!onCacheEntryAdded) return;\n    const lifecycle = {} as CacheLifecycle;\n    const cacheEntryRemoved = new Promise<void>(resolve => {\n      lifecycle.cacheEntryRemoved = resolve;\n    });\n    const cacheDataLoaded: PromiseWithKnownReason<{\n      data: unknown;\n      meta: unknown;\n    }, typeof neverResolvedError> = Promise.race([new Promise<{\n      data: unknown;\n      meta: unknown;\n    }>(resolve => {\n      lifecycle.valueResolved = resolve;\n    }), cacheEntryRemoved.then(() => {\n      throw neverResolvedError;\n    })]);\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {});\n    lifecycleMap[queryCacheKey] = lifecycle;\n    const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);\n    const extra = mwApi.dispatch((_, __, extra) => extra);\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n      cacheDataLoaded,\n      cacheEntryRemoved\n    };\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch(e => {\n      if (e === neverResolvedError) return;\n      throw e;\n    });\n  }\n  return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: {\n    apiUid\n  },\n  reducerPath\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n      }\n    }\n  };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler } from './types';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: {\n    endpointDefinitions\n  },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));\n  let pendingTagInvalidations: FullTagDescription<string>[] = [];\n  // Track via counter so we can avoid iterating over state every time\n  let pendingRequestCount = 0;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {\n      pendingRequestCount++;\n    }\n    if (isQueryEnd(action)) {\n      pendingRequestCount = Math.max(0, pendingRequestCount - 1);\n    }\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi);\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n    }\n  };\n  function hasPendingRequests() {\n    return pendingRequestCount > 0;\n  }\n  function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n    const rootState = mwApi.getState();\n    const state = rootState[reducerPath];\n    pendingTagInvalidations.push(...newTags);\n    if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests()) {\n      return;\n    }\n    const tags = pendingTagInvalidations;\n    pendingTagInvalidations = [];\n    if (tags.length === 0) return;\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values());\n      for (const {\n        queryCacheKey\n      } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey];\n        const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);\n        if (querySubState) {\n          if (subscriptionSubState.size === 0) {\n            mwApi.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            mwApi.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers, SubscribersInternal } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    currentPolls,\n    currentSubscriptions\n  } = internalState;\n\n  // Batching state for polling updates\n  const pendingPollingUpdates = new Set<string>();\n  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n      schedulePollingUpdate(action.payload.queryCacheKey, mwApi);\n    }\n    if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);\n    }\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n      startNextPoll(action.meta.arg, mwApi);\n    }\n    if (api.util.resetApiState.match(action)) {\n      clearPolls();\n      // Clear any pending updates\n      if (pollingUpdateTimer) {\n        clearTimeout(pollingUpdateTimer);\n        pollingUpdateTimer = null;\n      }\n      pendingPollingUpdates.clear();\n    }\n  };\n  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {\n    pendingPollingUpdates.add(queryCacheKey);\n    if (!pollingUpdateTimer) {\n      pollingUpdateTimer = setTimeout(() => {\n        // Process all pending updates in a single batch\n        for (const key of pendingPollingUpdates) {\n          updatePollingInterval({\n            queryCacheKey: key as any\n          }, api);\n        }\n        pendingPollingUpdates.clear();\n        pollingUpdateTimer = null;\n      }, 0);\n    }\n  }\n  function startNextPoll({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;\n    const {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) return;\n    const currentPoll = currentPolls.get(queryCacheKey);\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout);\n      currentPoll.timeout = undefined;\n    }\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    currentPolls.set(queryCacheKey, {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState));\n        }\n        startNextPoll({\n          queryCacheKey\n        }, api);\n      }, lowestPollingInterval)\n    });\n  }\n  function updatePollingInterval({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {\n      return;\n    }\n    const {\n      lowestPollingInterval\n    } = findLowestPollingInterval(subscriptions);\n\n    // HACK add extra data to track how many times this has been called in tests\n    // yes we're mutating a nonexistent field on a Map here\n    if (process.env.NODE_ENV === 'test') {\n      const updateCounters = (currentPolls as any).pollUpdateCounters ??= {};\n      updateCounters[queryCacheKey] ??= 0;\n      updateCounters[queryCacheKey]++;\n    }\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey);\n      return;\n    }\n    const currentPoll = currentPolls.get(queryCacheKey);\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({\n        queryCacheKey\n      }, api);\n    }\n  }\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls.get(key);\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout);\n    }\n    currentPolls.delete(key);\n  }\n  function clearPolls() {\n    for (const key of currentPolls.keys()) {\n      cleanupPollForKey(key);\n    }\n  }\n  function findLowestPollingInterval(subscribers: SubscribersInternal = new Map()) {\n    let skipPollingIfUnfocused: boolean | undefined = false;\n    let lowestPollingInterval = Number.POSITIVE_INFINITY;\n    for (const entry of subscribers.values()) {\n      if (!!entry.pollingInterval) {\n        lowestPollingInterval = Math.min(entry.pollingInterval!, lowestPollingInterval);\n        skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;\n      }\n    }\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    };\n  }\n  return handler;\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: BaseQueryMeta<BaseQuery>;\n  }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n  error: BaseQueryError<BaseQuery>;\n  /**\n   * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n   */\n  isUnhandledError: false;\n  /**\n   * The `meta` returned by the `baseQuery`\n   */\n  meta: BaseQueryMeta<BaseQuery>;\n} | {\n  error: unknown;\n  meta?: undefined;\n  /**\n   * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n   * There can not be made any assumption about the shape of `error`.\n   */\n  isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * import { messageCreated } from './notificationsSlice\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'))\n   *         try {\n   *           const { data } = await queryFulfilled\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'))\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'))\n   *         }\n   *       }\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk);\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    resolve(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    reject(value: QueryFulfilledRejectionReason<any>): unknown;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: {\n          endpointName,\n          originalArgs\n        }\n      } = action.meta;\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const onQueryStarted = endpointDefinition?.onQueryStarted;\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle;\n        const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n          data: unknown;\n          meta: unknown;\n        }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n          lifecycle.resolve = resolve;\n          lifecycle.reject = reject;\n        });\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {});\n        lifecycleMap[requestId] = lifecycle;\n        const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);\n        const extra = mwApi.dispatch((_, __, extra) => extra);\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n          queryFulfilled\n        };\n        onQueryStarted(originalArgs, lifecycleApi as any);\n      }\n    } else if (isFullfilledThunk(action)) {\n      const {\n        requestId,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta\n      });\n      delete lifecycleMap[requestId];\n    } else if (isRejectedThunk(action)) {\n      const {\n        requestId,\n        rejectedWithValue,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any\n      });\n      delete lifecycleMap[requestId];\n    }\n  };\n  return handler;\n};","import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus');\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect');\n    }\n  };\n  function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n    const state = api.getState()[reducerPath];\n    const queries = state.queries;\n    const subscriptions = internalState.currentSubscriptions;\n    context.batch(() => {\n      for (const queryCacheKey of subscriptions.keys()) {\n        const querySubState = queries[queryCacheKey];\n        const subscriptionSubState = subscriptions.get(queryCacheKey);\n        if (!subscriptionSubState || !querySubState) continue;\n        const values = [...subscriptionSubState.values()];\n        const shouldRefetch = values.some(sub => sub[type] === true) || values.every(sub => sub[type] === undefined) && state.config[type];\n        if (shouldRefetch) {\n          if (subscriptionSubState.size === 0) {\n            api.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            api.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const {\n    reducerPath,\n    queryThunk,\n    api,\n    context,\n    getInternalState\n  } = input;\n  const {\n    apiUid\n  } = context;\n  const actions = {\n    invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n  };\n  const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n  const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n  const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n    let initialized = false;\n    const internalState = getInternalState(mwApi.dispatch);\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction,\n      mwApi\n    };\n    const handlers = handlerBuilders.map(build => build(builderArgs));\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n    const windowEventsHandler = buildWindowEventHandler(builderArgs);\n    return next => {\n      return action => {\n        if (!isAction(action)) {\n          return next(action);\n        }\n        if (!initialized) {\n          initialized = true;\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n        }\n        const mwApiWithNext = {\n          ...mwApi,\n          next\n        };\n        const stateBefore = mwApi.getState();\n        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n        let res: any;\n        if (actionShouldContinue) {\n          res = next(action);\n        } else {\n          res = internalProbeResult;\n        }\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore);\n          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore);\n            }\n          }\n        }\n        return res;\n      };\n    };\n  };\n  return {\n    middleware,\n    actions\n  };\n  function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n    status: QueryStatus.uninitialized;\n  }>) {\n    return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true\n    });\n  }\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Dispatch, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from '../utils/immerImports';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nimport { getOrInsertComputed } from '../utils';\nimport type { CreateSelectorFunction } from 'reselect';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n */\nexport type PrefetchOptions = {\n  ifOlderThan?: false | number;\n} | {\n  force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath;\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions;\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n    /**\n     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'query';\n      }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'infinitequery';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n        type: 'mutation';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n       *\n       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n      /**\n       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n       *\n       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n       *\n       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n       *\n       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n       *\n       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n      /**\n       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n       *\n       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n       *\n       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState'];\n      upsertQueryEntries: UpsertEntries<Definitions>;\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n       *\n       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n       *\n       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n        endpointName: string;\n        originalArgs: any;\n        queryCacheKey: string;\n      }>;\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;\n    };\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never };\n  };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(api, {\n    baseQuery,\n    tagTypes,\n    reducerPath,\n    serializeQueryArgs,\n    keepUnusedDataFor,\n    refetchOnMountOrArgChange,\n    refetchOnFocus,\n    refetchOnReconnect,\n    invalidationBehavior,\n    onSchemaFailure,\n    catchSchemaFailure,\n    skipSchemaValidation\n  }, context) {\n    enablePatches();\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n    const assertTagType: AssertTagTypes = tag => {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n        }\n      }\n      return tag;\n    };\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost\n      },\n      util: {}\n    });\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector\n    });\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector\n    } = selectors;\n    safeAssign(api.util, {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery\n    });\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation\n    });\n    const {\n      reducer,\n      actions: sliceActions\n    } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior\n      }\n    });\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n    });\n    safeAssign(api.internalActions, sliceActions);\n    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>();\n    const getInternalState = (dispatch: Dispatch) => {\n      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({\n        currentSubscriptions: new Map(),\n        currentPolls: new Map(),\n        runningQueries: new Map(),\n        runningMutations: new Map()\n      }));\n      return state;\n    };\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context,\n      getInternalState\n    });\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk\n    });\n    const {\n      middleware,\n      actions: middlewareActions\n    } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors,\n      getRunningQueryThunk,\n      getInternalState\n    });\n    safeAssign(api.util, middlewareActions);\n    safeAssign(api, {\n      reducer: reducer as any,\n      middleware\n    });\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n        const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n        if (isQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildQuerySelector(endpointName, definition),\n            initiate: buildInitiateQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildMutationSelector(),\n            initiate: buildInitiateMutation(endpointName)\n          }, buildMatchThunkActions(mutationThunk, endpointName));\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildInfiniteQuerySelector(endpointName, definition),\n            initiate: buildInitiateInfiniteQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n      }\n    };\n  }\n});","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkEO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,mBAAgB;A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AW,IAAI,MAAM;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,UAAM;AAAA,MACJ;AAAA,MACA,SAAS;AAAA,IACX,IAAI,gBAAgB;AAAA,MAClB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,eAAW,IAAI,MAAM,iBAAiB;AACtC,eAAW,KAAK;AAAA,MACd;AAAA,MACA;AAAA,IACF,CAAC;AACD,WAAO;AAAA,MACL,MAAM;AAAA,MACN,eAAe,cAAc,YAAY;AACvC,cAAM,SAAS;AACf,cAAM,WAAW,OAAO,UAAU,YAAY,MAAM,CAAC;AACrD,YAAI,kBAAkB,UAAU,GAAG;AACjC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,mBAAmB,cAAc,UAAU;AAAA,YACnD,UAAU,mBAAmB,cAAc,UAAU;AAAA,UACvD,GAAG,uBAAuB,YAAY,YAAY,CAAC;AAAA,QACrD;AACA,YAAI,qBAAqB,UAAU,GAAG;AACpC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,sBAAsB;AAAA,YAC9B,UAAU,sBAAsB,YAAY;AAAA,UAC9C,GAAG,uBAAuB,eAAe,YAAY,CAAC;AAAA,QACxD;AACA,YAAI,0BAA0B,UAAU,GAAG;AACzC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,2BAA2B,cAAc,UAAU;AAAA,YAC3D,UAAU,2BAA2B,cAAc,UAAU;AAAA,UAC/D,GAAG,uBAAuB,YAAY,YAAY,CAAC;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACniBO,IAAM,YAA2B,+BAAe,WAAW,CAAC;","names":["QueryStatus","isPlainObject","retry","updateListeners","import_toolkit","import_utils","arg","force","options","actions","createSelector","import_toolkit","key","queryArgsApi","_formatProdErrorMessage","getPreviousPageParam","_formatProdErrorMessage2","import_toolkit","_formatProdErrorMessage","mwApi","mwApi","api","cacheKey","extra","api","extra","api","actions","initialized","createSelector"]}
Index: node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.production.min.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+"use strict";var He=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Jt=Object.prototype.hasOwnProperty;var Gt=(e,t)=>{for(var u in t)He(e,u,{get:t[u],enumerable:!0})},Zt=(e,t,u,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of Yt(t))!Jt.call(e,p)&&p!==u&&He(e,p,{get:()=>t[p],enumerable:!(l=$t(t,p))||l.enumerable});return e};var Xt=e=>Zt(He({},"__esModule",{value:!0}),e);var ln={};Gt(ln,{NamedSchemaError:()=>ce,QueryStatus:()=>Ve,_NEVER:()=>Ct,buildCreateApi:()=>Le,copyWithStructuralSharing:()=>Se,coreModule:()=>_e,coreModuleName:()=>Me,createApi:()=>jt,defaultSerializeQueryArgs:()=>ke,fakeBaseQuery:()=>Ft,fetchBaseQuery:()=>pt,retry:()=>lt,setupListeners:()=>Qt,skipToken:()=>Be});module.exports=Xt(ln);var Ve=(p=>(p.uninitialized="uninitialized",p.pending="pending",p.fulfilled="fulfilled",p.rejected="rejected",p))(Ve||{}),W="uninitialized",Fe="pending",ge="fulfilled",Qe="rejected";function je(e){return{status:e,isUninitialized:e===W,isLoading:e===Fe,isSuccess:e===ge,isError:e===Qe}}var s=require("@reduxjs/toolkit");var tt=s.isPlainObject;function Se(e,t){if(e===t||!(tt(e)&&tt(t)||Array.isArray(e)&&Array.isArray(t)))return t;let u=Object.keys(t),l=Object.keys(e),p=u.length===l.length,S=Array.isArray(t)?[]:{};for(let Q of u)S[Q]=Se(e[Q],t[Q]),p&&(p=e[Q]===S[Q]);return p?e:S}function xe(e,t,u){return e.reduce((l,p,S)=>(t(p,S)&&l.push(u(p,S)),l),[]).flat()}function nt(e){return new RegExp("(^|:)//").test(e)}function rt(){return typeof document>"u"?!0:document.visibilityState!=="hidden"}function De(e){return e!=null}function ze(e){return[...e?.values()??[]].filter(De)}function it(){return typeof navigator>"u"||navigator.onLine===void 0?!0:navigator.onLine}var en=e=>e.replace(/\/$/,""),tn=e=>e.replace(/^\//,"");function at(e,t){if(!e)return t;if(!t)return e;if(nt(t))return t;let u=e.endsWith("/")||!t.startsWith("?")?"/":"";return e=en(e),t=tn(t),`${e}${u}${t}`}function ye(e,t,u){return e.has(t)?e.get(t):e.set(t,u(t)).get(t)}var Ee=()=>new Map;var ot=e=>{let t=new AbortController;return setTimeout(()=>{let u="signal timed out",l="TimeoutError";t.abort(typeof DOMException<"u"?new DOMException(u,l):Object.assign(new Error(u),{name:l}))},e),t.signal},st=(...e)=>{for(let u of e)if(u.aborted)return AbortSignal.abort(u.reason);let t=new AbortController;for(let u of e)u.addEventListener("abort",()=>t.abort(u.reason),{signal:t.signal,once:!0});return t.signal};var ut=(...e)=>fetch(...e),nn=e=>e.status>=200&&e.status<=299,rn=e=>/ion\/(vnd\.api\+)?json/.test(e.get("content-type")||"");function yt(e){if(!(0,s.isPlainObject)(e))return e;let t={...e};for(let[u,l]of Object.entries(t))l===void 0&&delete t[u];return t}var an=e=>typeof e=="object"&&((0,s.isPlainObject)(e)||Array.isArray(e)||typeof e.toJSON=="function");function pt({baseUrl:e,prepareHeaders:t=h=>h,fetchFn:u=ut,paramsSerializer:l,isJsonContentType:p=rn,jsonContentType:S="application/json",jsonReplacer:Q,timeout:k,responseHandler:M,validateStatus:x,...D}={}){return typeof fetch>"u"&&u===ut&&console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."),async(R,b,w)=>{let{getState:P,extra:f,endpoint:A,forced:B,type:y}=b,c,{url:i,headers:T=new Headers(D.headers),params:E=void 0,responseHandler:g=M??"json",validateStatus:d=x??nn,timeout:a=k,...n}=typeof R=="string"?{url:R}:R,r={...D,signal:a?st(b.signal,ot(a)):b.signal,...n};T=new Headers(yt(T)),r.headers=await t(T,{getState:P,arg:R,extra:f,endpoint:A,forced:B,type:y,extraOptions:w})||T;let o=an(r.body);if(r.body!=null&&!o&&typeof r.body!="string"&&r.headers.delete("content-type"),!r.headers.has("content-type")&&o&&r.headers.set("content-type",S),o&&p(r.headers)&&(r.body=JSON.stringify(r.body,Q)),r.headers.has("accept")||(g==="json"?r.headers.set("accept","application/json"):g==="text"&&r.headers.set("accept","text/plain, text/html, */*")),E){let O=~i.indexOf("?")?"&":"?",_=l?l(E):new URLSearchParams(yt(E));i+=O+_}i=at(e,i);let m=new Request(i,r);c={request:new Request(i,r)};let C;try{C=await u(m)}catch(O){return{error:{status:(O instanceof Error||typeof DOMException<"u"&&O instanceof DOMException)&&O.name==="TimeoutError"?"TIMEOUT_ERROR":"FETCH_ERROR",error:String(O)},meta:c}}let N=C.clone();c.response=N;let v,I="";try{let O;if(await Promise.all([h(C,g).then(_=>v=_,_=>O=_),N.text().then(_=>I=_,()=>{})]),O)throw O}catch(O){return{error:{status:"PARSING_ERROR",originalStatus:C.status,data:I,error:String(O)},meta:c}}return d(C,v)?{data:v,meta:c}:{error:{status:C.status,data:v},meta:c}};async function h(R,b){if(typeof b=="function")return b(R);if(b==="content-type"&&(b=p(R.headers)?"json":"text"),b==="json"){let w=await R.text();return w.length?JSON.parse(w):null}return R.text()}}var Z=class{constructor(t,u=void 0){this.value=t;this.meta=u}};async function on(e=0,t=5,u){let l=Math.min(e,t),p=~~((Math.random()+.4)*(300<<l));await new Promise((S,Q)=>{let k=setTimeout(()=>S(),p);if(u){let M=()=>{clearTimeout(k),Q(new Error("Aborted"))};u.aborted?(clearTimeout(k),Q(new Error("Aborted"))):u.addEventListener("abort",M,{once:!0})}})}function ct(e,t){throw Object.assign(new Z({error:e,meta:t}),{throwImmediately:!0})}function We(e){e.aborted&&ct({status:"CUSTOM_ERROR",error:"Aborted"})}var dt={},sn=(e,t)=>async(u,l,p)=>{let S=[5,(t||dt).maxRetries,(p||dt).maxRetries].filter(D=>D!==void 0),[Q]=S.slice(-1),M={maxRetries:Q,backoff:on,retryCondition:(D,h,{attempt:R})=>R<=Q,...t,...p},x=0;for(;;){We(l.signal);try{let D=await e(u,l,p);if(D.error)throw new Z(D);return D}catch(D){if(x++,D.throwImmediately){if(D instanceof Z)return D.value;throw D}if(D instanceof Z){if(!M.retryCondition(D.value.error,u,{attempt:x,baseQueryApi:l,extraOptions:p}))return D.value}else if(x>M.maxRetries)return{error:D};We(l.signal);try{await M.backoff(x,M.maxRetries,l.signal)}catch(h){throw We(l.signal),h}}}},lt=Object.assign(sn,{fail:ct});var Oe="__rtkq/",ft="online",mt="offline",un="focus",gt="focused",yn="visibilitychange",ie=(0,s.createAction)(`${Oe}${gt}`),Te=(0,s.createAction)(`${Oe}un${gt}`),ae=(0,s.createAction)(`${Oe}${ft}`),he=(0,s.createAction)(`${Oe}${mt}`),pn={onFocus:ie,onFocusLost:Te,onOnline:ae,onOffline:he},ve=!1;function Qt(e,t){function u(){let[l,p,S,Q]=[ie,Te,ae,he].map(D=>()=>e(D())),k=()=>{window.document.visibilityState==="visible"?l():p()},M=()=>{ve=!1};if(!ve&&typeof window<"u"&&window.addEventListener){let h=function(R){Object.entries(D).forEach(([b,w])=>{R?window.addEventListener(b,w,!1):window.removeEventListener(b,w)})};var x=h;let D={[un]:l,[yn]:k,[ft]:S,[mt]:Q};h(!0),ve=!0,M=()=>{h(!1),ve=!1}}return M}return t?t(e,pn):u()}var te="query",$e="mutation",Ye="infinitequery";function pe(e){return e.type===te}function Tt(e){return e.type===$e}function de(e){return e.type===Ye}function Re(e){return pe(e)||de(e)}function be(e,t,u,l,p,S){let Q=dn(e)?e(t,u,l,p):e;return Q?xe(Q,De,k=>S(Je(k))):[]}function dn(e){return typeof e=="function"}function Je(e){return typeof e=="string"?{type:e}:e}var H=require("immer");var Hn=require("@reduxjs/toolkit");function ht(e,t){return e.catch(t)}var J=(e,t)=>e.endpointDefinitions[t];var Ae=Symbol("forceQueryFn"),Pe=e=>typeof e[Ae]=="function";function Rt({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:u,mutationThunk:l,api:p,context:S,getInternalState:Q}){let k=i=>Q(i)?.runningQueries,M=i=>Q(i)?.runningMutations,{unsubscribeQueryResult:x,removeMutationResult:D,updateSubscriptionOptions:h}=p.internalActions;return{buildInitiateQuery:B,buildInitiateInfiniteQuery:y,buildInitiateMutation:c,getRunningQueryThunk:R,getRunningMutationThunk:b,getRunningQueriesThunk:w,getRunningMutationsThunk:P};function R(i,T){return E=>{let g=J(S,i),d=e({queryArgs:T,endpointDefinition:g,endpointName:i});return k(E)?.get(d)}}function b(i,T){return E=>M(E)?.get(T)}function w(){return i=>ze(k(i))}function P(){return i=>ze(M(i))}function f(i){}function A(i,T){let E=(g,{subscribe:d=!0,forceRefetch:a,subscriptionOptions:n,[Ae]:r,...o}={})=>(m,F)=>{let C=e({queryArgs:g,endpointDefinition:T,endpointName:i}),N,v={...o,type:te,subscribe:d,forceRefetch:a,subscriptionOptions:n,endpointName:i,originalArgs:g,queryCacheKey:C,[Ae]:r};if(pe(T))N=t(v);else{let{direction:K,initialPageParam:L,refetchCachedPages:U}=o;N=u({...v,direction:K,initialPageParam:L,refetchCachedPages:U})}let I=p.endpoints[i].select(g),O=m(N),_=I(F());let{requestId:$,abort:G}=O,V=_.requestId!==$,z=k(m)?.get(C),j=()=>I(F()),q=Object.assign(r?O.then(j):V&&!z?Promise.resolve(_):Promise.all([z,O]).then(j),{arg:g,requestId:$,subscriptionOptions:n,queryCacheKey:C,abort:G,async unwrap(){let K=await q;if(K.isError)throw K.error;return K.data},refetch:K=>m(E(g,{subscribe:!1,forceRefetch:!0,...K})),unsubscribe(){d&&m(x({queryCacheKey:C,requestId:$}))},updateSubscriptionOptions(K){q.subscriptionOptions=K,m(h({endpointName:i,requestId:$,queryCacheKey:C,options:K}))}});if(!z&&!V&&!r){let K=k(m);K.set(C,q),q.then(()=>{K.delete(C)})}return q};return E}function B(i,T){return A(i,T)}function y(i,T){return A(i,T)}function c(i){return(T,{track:E=!0,fixedCacheKey:g}={})=>(d,a)=>{let n=l({type:"mutation",endpointName:i,originalArgs:T,track:E,fixedCacheKey:g}),r=d(n);let{requestId:o,abort:m,unwrap:F}=r,C=ht(r.unwrap().then(O=>({data:O})),O=>({error:O})),N=()=>{d(D({requestId:o,fixedCacheKey:g}))},v=Object.assign(C,{arg:r.arg,requestId:o,abort:m,unwrap:F,reset:N}),I=M(d);return I.set(o,v),v.then(()=>{I.delete(o)}),g&&(I.set(g,v),v.then(()=>{I.get(g)===v&&I.delete(g)})),v}}}var At=require("@standard-schema/utils"),ce=class extends At.SchemaError{constructor(u,l,p,S){super(u);this.value=l;this.schemaName=p;this._bqMeta=S}},oe=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function se(e,t,u,l){let p=await e["~standard"].validate(t);if(p.issues)throw new ce(p.issues,t,u,l);return p.value}function St(e){return e}var Ie=(e={})=>({...e,[s.SHOULD_AUTOBATCH]:!0});function xt({reducerPath:e,baseQuery:t,context:{endpointDefinitions:u},serializeQueryArgs:l,api:p,assertTagType:S,selectors:Q,onSchemaFailure:k,catchSchemaFailure:M,skipSchemaValidation:x}){let D=(n,r,o,m)=>(F,C)=>{let N=u[n],v=l({queryArgs:r,endpointDefinition:N,endpointName:n});if(F(p.internalActions.queryResultPatched({queryCacheKey:v,patches:o})),!m)return;let I=p.endpoints[n].select(r)(C()),O=be(N.providesTags,I.data,void 0,r,{},S);F(p.internalActions.updateProvidedBy([{queryCacheKey:v,providedTags:O}]))};function h(n,r,o=0){let m=[r,...n];return o&&m.length>o?m.slice(0,-1):m}function R(n,r,o=0){let m=[...n,r];return o&&m.length>o?m.slice(1):m}let b=(n,r,o,m=!0)=>(F,C)=>{let v=p.endpoints[n].select(r)(C()),I={patches:[],inversePatches:[],undo:()=>F(p.util.patchQueryData(n,r,I.inversePatches,m))};if(v.status===W)return I;let O;if("data"in v)if((0,H.isDraftable)(v.data)){let[_,$,G]=(0,H.produceWithPatches)(v.data,o);I.patches.push(...$),I.inversePatches.push(...G),O=_}else O=o(v.data),I.patches.push({op:"replace",path:[],value:O}),I.inversePatches.push({op:"replace",path:[],value:v.data});return I.patches.length===0||F(p.util.patchQueryData(n,r,I.patches,m)),I},w=(n,r,o)=>m=>m(p.endpoints[n].initiate(r,{subscribe:!1,forceRefetch:!0,[Ae]:()=>({data:o})})),P=(n,r)=>n.query&&n[r]?n[r]:St,f=async(n,{signal:r,abort:o,rejectWithValue:m,fulfillWithValue:F,dispatch:C,getState:N,extra:v})=>{let I=u[n.endpointName],{metaSchema:O,skipSchemaValidation:_=x}=I,$=n.type===te;try{let G=St,V={signal:r,abort:o,dispatch:C,getState:N,extra:v,endpoint:n.endpointName,type:n.type,forced:$?A(n,N()):void 0,queryCacheKey:$?n.queryCacheKey:void 0},z=$?n[Ae]:void 0,j,q=async(L,U,ne,Y)=>{if(U==null&&L.pages.length)return Promise.resolve({data:L});let fe={queryArg:n.originalArgs,pageParam:U},ee=await K(fe),me=Y?h:R;return{data:{pages:me(L.pages,ee.data,ne),pageParams:me(L.pageParams,U,ne)},meta:ee.meta}};async function K(L){let U,{extraOptions:ne,argSchema:Y,rawResponseSchema:fe,responseSchema:ee}=I;if(Y&&!oe(_,"arg")&&(L=await se(Y,L,"argSchema",{})),z?U=z():I.query?(G=P(I,"transformResponse"),U=await t(I.query(L),V,ne)):U=await I.queryFn(L,V,ne,ue=>t(ue,V,ne)),typeof process<"u",U.error)throw new Z(U.error,U.meta);let{data:me}=U;fe&&!oe(_,"rawResponse")&&(me=await se(fe,U.data,"rawResponseSchema",U.meta));let re=await G(me,U.meta,L);return ee&&!oe(_,"response")&&(re=await se(ee,re,"responseSchema",U.meta)),{...U,data:re}}if($&&"infiniteQueryOptions"in I){let{infiniteQueryOptions:L}=I,{maxPages:U=1/0}=L,ne=n.refetchCachedPages??L.refetchCachedPages??!0,Y,fe={pages:[],pageParams:[]},ee=Q.selectQueryEntry(N(),n.queryCacheKey)?.data,re=A(n,N())&&!n.direction||!ee?fe:ee;if("direction"in n&&n.direction&&re.pages.length){let ue=n.direction==="backward",Ce=(ue?Ge:Ne)(L,re,n.originalArgs);Y=await q(re,Ce,U,ue)}else{let{initialPageParam:ue=L.initialPageParam}=n,we=ee?.pageParams??[],Ce=we[0]??ue,zt=we.length;if(Y=await q(re,Ce,U),z&&(Y={data:Y.data.pages[0]}),ne)for(let et=1;et<zt;et++){let Wt=Ne(L,Y.data,n.originalArgs);Y=await q(Y.data,Wt,U)}}j=Y}else j=await K(n.originalArgs);return O&&!oe(_,"meta")&&j.meta&&(j.meta=await se(O,j.meta,"metaSchema",j.meta)),F(j.data,Ie({fulfilledTimeStamp:Date.now(),baseQueryMeta:j.meta}))}catch(G){let V=G;if(V instanceof Z){let z=P(I,"transformErrorResponse"),{rawErrorResponseSchema:j,errorResponseSchema:q}=I,{value:K,meta:L}=V;try{j&&!oe(_,"rawErrorResponse")&&(K=await se(j,K,"rawErrorResponseSchema",L)),O&&!oe(_,"meta")&&(L=await se(O,L,"metaSchema",L));let U=await z(K,L,n.originalArgs);return q&&!oe(_,"errorResponse")&&(U=await se(q,U,"errorResponseSchema",L)),m(U,Ie({baseQueryMeta:L}))}catch(U){V=U}}try{if(V instanceof ce){let z={endpoint:n.endpointName,arg:n.originalArgs,type:n.type,queryCacheKey:$?n.queryCacheKey:void 0};I.onSchemaFailure?.(V,z),k?.(V,z);let{catchSchemaFailure:j=M}=I;if(j)return m(j(V,z),Ie({baseQueryMeta:V._bqMeta}))}}catch(z){V=z}throw typeof process<"u",console.error(V),V}};function A(n,r){let o=Q.selectQueryEntry(r,n.queryCacheKey),m=Q.selectConfig(r).refetchOnMountOrArgChange,F=o?.fulfilledTimeStamp,C=n.forceRefetch??(n.subscribe&&m);return C?C===!0||(Number(new Date)-Number(F))/1e3>=C:!1}let B=()=>(0,s.createAsyncThunk)(`${e}/executeQuery`,f,{getPendingMeta({arg:r}){let o=u[r.endpointName];return Ie({startedTimeStamp:Date.now(),...de(o)?{direction:r.direction}:{}})},condition(r,{getState:o}){let m=o(),F=Q.selectQueryEntry(m,r.queryCacheKey),C=F?.fulfilledTimeStamp,N=r.originalArgs,v=F?.originalArgs,I=u[r.endpointName],O=r.direction;return Pe(r)?!0:F?.status==="pending"?!1:A(r,m)||pe(I)&&I?.forceRefetch?.({currentArg:N,previousArg:v,endpointState:F,state:m})?!0:!(C&&!O)},dispatchConditionRejection:!0}),y=B(),c=B(),i=(0,s.createAsyncThunk)(`${e}/executeMutation`,f,{getPendingMeta(){return Ie({startedTimeStamp:Date.now()})}}),T=n=>"force"in n,E=n=>"ifOlderThan"in n,g=(n,r,o={})=>(m,F)=>{let C=T(o)&&o.force,N=E(o)&&o.ifOlderThan,v=(O=!0)=>{let _={forceRefetch:O,subscribe:!1};return p.endpoints[n].initiate(r,_)},I=p.endpoints[n].select(r)(F());if(C)m(v());else if(N){let O=I?.fulfilledTimeStamp;if(!O){m(v());return}(Number(new Date)-Number(new Date(O)))/1e3>=N&&m(v())}else m(v(!1))};function d(n){return r=>r?.meta?.arg?.endpointName===n}function a(n,r){return{matchPending:(0,s.isAllOf)((0,s.isPending)(n),d(r)),matchFulfilled:(0,s.isAllOf)((0,s.isFulfilled)(n),d(r)),matchRejected:(0,s.isAllOf)((0,s.isRejected)(n),d(r))}}return{queryThunk:y,mutationThunk:i,infiniteQueryThunk:c,prefetch:g,updateQueryData:b,upsertQueryData:w,patchQueryData:D,buildMatchThunkActions:a}}function Ne(e,{pages:t,pageParams:u},l){let p=t.length-1;return e.getNextPageParam(t[p],t,u[p],u,l)}function Ge(e,{pages:t,pageParams:u},l){return e.getPreviousPageParam?.(t[0],t,u[0],u,l)}function Ue(e,t,u,l){return be(u[e.meta.arg.endpointName][t],(0,s.isFulfilled)(e)?e.payload:void 0,(0,s.isRejectedWithValue)(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,l)}function Ze(e){return(0,H.isDraft)(e)?(0,H.current)(e):e}function qe(e,t,u){let l=e[t];l&&u(l)}function le(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Dt(e,t,u){let l=e[le(t)];l&&u(l)}var Ke={};function Et({reducerPath:e,queryThunk:t,mutationThunk:u,serializeQueryArgs:l,context:{endpointDefinitions:p,apiUid:S,extractRehydrationInfo:Q,hasRehydrationInfo:k},assertTagType:M,config:x}){let D=(0,s.createAction)(`${e}/resetApiState`);function h(d,a,n,r){d[a.queryCacheKey]??={status:W,endpointName:a.endpointName},qe(d,a.queryCacheKey,o=>{o.status=Fe,o.requestId=n&&o.requestId?o.requestId:r.requestId,a.originalArgs!==void 0&&(o.originalArgs=a.originalArgs),o.startedTimeStamp=r.startedTimeStamp;let m=p[r.arg.endpointName];de(m)&&"direction"in a&&(o.direction=a.direction)})}function R(d,a,n,r){qe(d,a.arg.queryCacheKey,o=>{if(o.requestId!==a.requestId&&!r)return;let{merge:m}=p[a.arg.endpointName];if(o.status=ge,m)if(o.data!==void 0){let{fulfilledTimeStamp:F,arg:C,baseQueryMeta:N,requestId:v}=a,I=(0,s.createNextState)(o.data,O=>m(O,n,{arg:C.originalArgs,baseQueryMeta:N,fulfilledTimeStamp:F,requestId:v}));o.data=I}else o.data=n;else o.data=p[a.arg.endpointName].structuralSharing??!0?Se((0,H.isDraft)(o.data)?(0,H.original)(o.data):o.data,n):n;delete o.error,o.fulfilledTimeStamp=a.fulfilledTimeStamp})}let b=(0,s.createSlice)({name:`${e}/queries`,initialState:Ke,reducers:{removeQueryResult:{reducer(d,{payload:{queryCacheKey:a}}){delete d[a]},prepare:(0,s.prepareAutoBatched)()},cacheEntriesUpserted:{reducer(d,a){for(let n of a.payload){let{queryDescription:r,value:o}=n;h(d,r,!0,{arg:r,requestId:a.meta.requestId,startedTimeStamp:a.meta.timestamp}),R(d,{arg:r,requestId:a.meta.requestId,fulfilledTimeStamp:a.meta.timestamp,baseQueryMeta:{}},o,!0)}},prepare:d=>({payload:d.map(r=>{let{endpointName:o,arg:m,value:F}=r,C=p[o];return{queryDescription:{type:te,endpointName:o,originalArgs:r.arg,queryCacheKey:l({queryArgs:m,endpointDefinition:C,endpointName:o})},value:F}}),meta:{[s.SHOULD_AUTOBATCH]:!0,requestId:(0,s.nanoid)(),timestamp:Date.now()}})},queryResultPatched:{reducer(d,{payload:{queryCacheKey:a,patches:n}}){qe(d,a,r=>{r.data=(0,H.applyPatches)(r.data,n.concat())})},prepare:(0,s.prepareAutoBatched)()}},extraReducers(d){d.addCase(t.pending,(a,{meta:n,meta:{arg:r}})=>{let o=Pe(r);h(a,r,o,n)}).addCase(t.fulfilled,(a,{meta:n,payload:r})=>{let o=Pe(n.arg);R(a,n,r,o)}).addCase(t.rejected,(a,{meta:{condition:n,arg:r,requestId:o},error:m,payload:F})=>{qe(a,r.queryCacheKey,C=>{if(!n){if(C.requestId!==o)return;C.status=Qe,C.error=F??m}})}).addMatcher(k,(a,n)=>{let{queries:r}=Q(n);for(let[o,m]of Object.entries(r))(m?.status===ge||m?.status===Qe)&&(a[o]=m)})}}),w=(0,s.createSlice)({name:`${e}/mutations`,initialState:Ke,reducers:{removeMutationResult:{reducer(d,{payload:a}){let n=le(a);n in d&&delete d[n]},prepare:(0,s.prepareAutoBatched)()}},extraReducers(d){d.addCase(u.pending,(a,{meta:n,meta:{requestId:r,arg:o,startedTimeStamp:m}})=>{o.track&&(a[le(n)]={requestId:r,status:Fe,endpointName:o.endpointName,startedTimeStamp:m})}).addCase(u.fulfilled,(a,{payload:n,meta:r})=>{r.arg.track&&Dt(a,r,o=>{o.requestId===r.requestId&&(o.status=ge,o.data=n,o.fulfilledTimeStamp=r.fulfilledTimeStamp)})}).addCase(u.rejected,(a,{payload:n,error:r,meta:o})=>{o.arg.track&&Dt(a,o,m=>{m.requestId===o.requestId&&(m.status=Qe,m.error=n??r)})}).addMatcher(k,(a,n)=>{let{mutations:r}=Q(n);for(let[o,m]of Object.entries(r))(m?.status===ge||m?.status===Qe)&&o!==m?.requestId&&(a[o]=m)})}}),P={tags:{},keys:{}},f=(0,s.createSlice)({name:`${e}/invalidation`,initialState:P,reducers:{updateProvidedBy:{reducer(d,a){for(let{queryCacheKey:n,providedTags:r}of a.payload){A(d,n);for(let{type:o,id:m}of r){let F=(d.tags[o]??={})[m||"__internal_without_id"]??=[];F.includes(n)||F.push(n)}d.keys[n]=r}},prepare:(0,s.prepareAutoBatched)()}},extraReducers(d){d.addCase(b.actions.removeQueryResult,(a,{payload:{queryCacheKey:n}})=>{A(a,n)}).addMatcher(k,(a,n)=>{let{provided:r}=Q(n);for(let[o,m]of Object.entries(r.tags??{}))for(let[F,C]of Object.entries(m)){let N=(a.tags[o]??={})[F||"__internal_without_id"]??=[];for(let v of C)N.includes(v)||N.push(v),a.keys[v]=r.keys[v]}}).addMatcher((0,s.isAnyOf)((0,s.isFulfilled)(t),(0,s.isRejectedWithValue)(t)),(a,n)=>{B(a,[n])}).addMatcher(b.actions.cacheEntriesUpserted.match,(a,n)=>{let r=n.payload.map(({queryDescription:o,value:m})=>({type:"UNKNOWN",payload:m,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:o}}));B(a,r)})}});function A(d,a){let n=Ze(d.keys[a]??[]);for(let r of n){let o=r.type,m=r.id??"__internal_without_id",F=d.tags[o]?.[m];F&&(d.tags[o][m]=Ze(F).filter(C=>C!==a))}delete d.keys[a]}function B(d,a){let n=a.map(r=>{let o=Ue(r,"providesTags",p,M),{queryCacheKey:m}=r.meta.arg;return{queryCacheKey:m,providedTags:o}});f.caseReducers.updateProvidedBy(d,f.actions.updateProvidedBy(n))}let y=(0,s.createSlice)({name:`${e}/subscriptions`,initialState:Ke,reducers:{updateSubscriptionOptions(d,a){},unsubscribeQueryResult(d,a){},internal_getRTKQSubscriptions(){}}}),c=(0,s.createSlice)({name:`${e}/internalSubscriptions`,initialState:Ke,reducers:{subscriptionsUpdated:{reducer(d,a){return(0,H.applyPatches)(d,a.payload)},prepare:(0,s.prepareAutoBatched)()}}}),i=(0,s.createSlice)({name:`${e}/config`,initialState:{online:it(),focused:rt(),middlewareRegistered:!1,...x},reducers:{middlewareRegistered(d,{payload:a}){d.middlewareRegistered=d.middlewareRegistered==="conflict"||S!==a?"conflict":!0}},extraReducers:d=>{d.addCase(ae,a=>{a.online=!0}).addCase(he,a=>{a.online=!1}).addCase(ie,a=>{a.focused=!0}).addCase(Te,a=>{a.focused=!1}).addMatcher(k,a=>({...a}))}}),T=(0,s.combineReducers)({queries:b.reducer,mutations:w.reducer,provided:f.reducer,subscriptions:c.reducer,config:i.reducer}),E=(d,a)=>T(D.match(a)?void 0:d,a),g={...i.actions,...b.actions,...y.actions,...c.actions,...w.actions,...f.actions,resetApiState:D};return{reducer:E,actions:g}}var Be=Symbol.for("RTKQ/skipToken"),It={status:W},bt=(0,s.createNextState)(It,()=>{}),Pt=(0,s.createNextState)(It,()=>{});function Bt({serializeQueryArgs:e,reducerPath:t,createSelector:u}){let l=y=>bt,p=y=>Pt;return{buildQuerySelector:R,buildInfiniteQuerySelector:b,buildMutationSelector:w,selectInvalidatedBy:P,selectCachedArgsForQuery:f,selectApiState:Q,selectQueries:k,selectMutations:x,selectQueryEntry:M,selectConfig:D};function S(y){return{...y,...je(y.status)}}function Q(y){return y[t]}function k(y){return Q(y)?.queries}function M(y,c){return k(y)?.[c]}function x(y){return Q(y)?.mutations}function D(y){return Q(y)?.config}function h(y,c,i){return T=>{if(T===Be)return u(l,i);let E=e({queryArgs:T,endpointDefinition:c,endpointName:y});return u(d=>M(d,E)??bt,i)}}function R(y,c){return h(y,c,S)}function b(y,c){let{infiniteQueryOptions:i}=c;function T(E){let g={...E,...je(E.status)},{isLoading:d,isError:a,direction:n}=g,r=n==="forward",o=n==="backward";return{...g,hasNextPage:A(i,g.data,g.originalArgs),hasPreviousPage:B(i,g.data,g.originalArgs),isFetchingNextPage:d&&r,isFetchingPreviousPage:d&&o,isFetchNextPageError:a&&r,isFetchPreviousPageError:a&&o}}return h(y,c,T)}function w(){return y=>{let c;return typeof y=="object"?c=le(y)??Be:c=y,u(c===Be?p:E=>Q(E)?.mutations?.[c]??Pt,S)}}function P(y,c){let i=y[t],T=new Set,E=xe(c,De,Je);for(let g of E){let d=i.provided.tags[g.type];if(!d)continue;let a=(g.id!==void 0?d[g.id]:Object.values(d).flat())??[];for(let n of a)T.add(n)}return Array.from(T.values()).flatMap(g=>{let d=i.queries[g];return d?{queryCacheKey:g,endpointName:d.endpointName,originalArgs:d.originalArgs}:[]})}function f(y,c){return xe(Object.values(k(y)),i=>i?.endpointName===c&&i.status!==W,i=>i.originalArgs)}function A(y,c,i){return c?Ne(y,c,i)!=null:!1}function B(y,c,i){return!c||!y.getPreviousPageParam?!1:Ge(y,c,i)!=null}}var Mt=require("@reduxjs/toolkit");var kt=WeakMap?new WeakMap:void 0,ke=({endpointName:e,queryArgs:t})=>{let u="",l=kt?.get(t);if(typeof l=="string")u=l;else{let p=JSON.stringify(t,(S,Q)=>(Q=typeof Q=="bigint"?{$bigint:Q.toString()}:Q,Q=(0,s.isPlainObject)(Q)?Object.keys(Q).sort().reduce((k,M)=>(k[M]=Q[M],k),{}):Q,Q));(0,s.isPlainObject)(t)&&kt?.set(t,p),u=p}return`${e}(${u})`};var Xe=require("reselect");function Le(...e){return function(u){let l=(0,Xe.weakMapMemoize)(x=>u.extractRehydrationInfo?.(x,{reducerPath:u.reducerPath??"api"})),p={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...u,extractRehydrationInfo:l,serializeQueryArgs(x){let D=ke;if("serializeQueryArgs"in x.endpointDefinition){let h=x.endpointDefinition.serializeQueryArgs;D=R=>{let b=h(R);return typeof b=="string"?b:ke({...R,queryArgs:b})}}else u.serializeQueryArgs&&(D=u.serializeQueryArgs);return D(x)},tagTypes:[...u.tagTypes||[]]},S={endpointDefinitions:{},batch(x){x()},apiUid:(0,s.nanoid)(),extractRehydrationInfo:l,hasRehydrationInfo:(0,Xe.weakMapMemoize)(x=>l(x)!=null)},Q={injectEndpoints:M,enhanceEndpoints({addTagTypes:x,endpoints:D}){if(x)for(let h of x)p.tagTypes.includes(h)||p.tagTypes.push(h);if(D)for(let[h,R]of Object.entries(D))typeof R=="function"?R(J(S,h)):Object.assign(J(S,h)||{},R);return Q}},k=e.map(x=>x.init(Q,p,S));function M(x){let D=x.endpoints({query:h=>({...h,type:te}),mutation:h=>({...h,type:$e}),infiniteQuery:h=>({...h,type:Ye})});for(let[h,R]of Object.entries(D)){if(x.overrideExisting!==!0&&h in S.endpointDefinitions){if(x.overrideExisting==="throw")throw new Error((0,Mt.formatProdErrorMessage)(39));typeof process<"u";continue}typeof process<"u",S.endpointDefinitions[h]=R;for(let b of k)b.injectEndpoint(h,R)}return Q}return Q.injectEndpoints({endpoints:u.endpoints})}}var wt=require("@reduxjs/toolkit"),Ct=Symbol();function Ft(){return function(){throw new Error((0,wt.formatProdErrorMessage)(33))}}function X(e,...t){return Object.assign(e,...t)}var vt=({api:e,queryThunk:t,internalState:u,mwApi:l})=>{let p=`${e.reducerPath}/subscriptions`,S=null,Q=null,{updateSubscriptionOptions:k,unsubscribeQueryResult:M}=e.internalActions,x=(P,f)=>{if(k.match(f)){let{queryCacheKey:B,requestId:y,options:c}=f.payload,i=P.get(B);return i?.has(y)&&i.set(y,c),!0}if(M.match(f)){let{queryCacheKey:B,requestId:y}=f.payload,c=P.get(B);return c&&c.delete(y),!0}if(e.internalActions.removeQueryResult.match(f))return P.delete(f.payload.queryCacheKey),!0;if(t.pending.match(f)){let{meta:{arg:B,requestId:y}}=f,c=ye(P,B.queryCacheKey,Ee);return B.subscribe&&c.set(y,B.subscriptionOptions??c.get(y)??{}),!0}let A=!1;if(t.rejected.match(f)){let{meta:{condition:B,arg:y,requestId:c}}=f;if(B&&y.subscribe){let i=ye(P,y.queryCacheKey,Ee);i.set(c,y.subscriptionOptions??i.get(c)??{}),A=!0}}return A},D=()=>u.currentSubscriptions,b={getSubscriptions:D,getSubscriptionCount:P=>D().get(P)?.size??0,isRequestSubscribed:(P,f)=>!!D()?.get(P)?.get(f)};function w(P){return JSON.parse(JSON.stringify(Object.fromEntries([...P].map(([f,A])=>[f,Object.fromEntries(A)]))))}return(P,f)=>{if(S||(S=w(u.currentSubscriptions)),e.util.resetApiState.match(P))return S={},u.currentSubscriptions.clear(),Q=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(P))return[!1,b];let A=x(u.currentSubscriptions,P),B=!0;if(A){Q||(Q=setTimeout(()=>{let i=w(u.currentSubscriptions),[,T]=(0,H.produceWithPatches)(S,()=>i);f.next(e.internalActions.subscriptionsUpdated(T)),S=i,Q=null},500));let y=typeof P.type=="string"&&!!P.type.startsWith(p),c=t.rejected.match(P)&&P.meta.condition&&!!P.meta.arg.subscribe;B=!y&&!c}return[B,!1]}};var cn=2147483647/1e3-1,Ot=({reducerPath:e,api:t,queryThunk:u,context:l,internalState:p,selectors:{selectQueryEntry:S,selectConfig:Q},getRunningQueryThunk:k,mwApi:M})=>{let{removeQueryResult:x,unsubscribeQueryResult:D,cacheEntriesUpserted:h}=t.internalActions,R=(0,s.isAnyOf)(D.match,u.fulfilled,u.rejected,h.match);function b(y){let c=p.currentSubscriptions.get(y);return c?c.size>0:!1}let w={};function P(y){for(let c of y.values())c?.abort?.()}let f=(y,c)=>{let i=c.getState(),T=Q(i);if(R(y)){let E;if(h.match(y))E=y.payload.map(g=>g.queryDescription.queryCacheKey);else{let{queryCacheKey:g}=D.match(y)?y.payload:y.meta.arg;E=[g]}A(E,c,T)}if(t.util.resetApiState.match(y)){for(let[E,g]of Object.entries(w))g&&clearTimeout(g),delete w[E];P(p.runningQueries),P(p.runningMutations)}if(l.hasRehydrationInfo(y)){let{queries:E}=l.extractRehydrationInfo(y);A(Object.keys(E),c,T)}};function A(y,c,i){let T=c.getState();for(let E of y){let g=S(T,E);g?.endpointName&&B(E,g.endpointName,c,i)}}function B(y,c,i,T){let g=J(l,c)?.keepUnusedDataFor??T.keepUnusedDataFor;if(g===1/0)return;let d=Math.max(0,Math.min(g,cn));if(!b(y)){let a=w[y];a&&clearTimeout(a),w[y]=setTimeout(()=>{if(!b(y)){let n=S(i.getState(),y);n?.endpointName&&i.dispatch(k(n.endpointName,n.originalArgs))?.abort(),i.dispatch(x({queryCacheKey:y}))}delete w[y]},d*1e3)}}return f};var Nt=new Error("Promise never resolved before cacheEntryRemoved."),Ut=({api:e,reducerPath:t,context:u,queryThunk:l,mutationThunk:p,internalState:S,selectors:{selectQueryEntry:Q,selectApiState:k}})=>{let M=(0,s.isAsyncThunkAction)(l),x=(0,s.isAsyncThunkAction)(p),D=(0,s.isFulfilled)(l,p),h={},{removeQueryResult:R,removeMutationResult:b,cacheEntriesUpserted:w}=e.internalActions;function P(i,T,E){let g=h[i];g?.valueResolved&&(g.valueResolved({data:T,meta:E}),delete g.valueResolved)}function f(i){let T=h[i];T&&(delete h[i],T.cacheEntryRemoved())}function A(i){let{arg:T,requestId:E}=i.meta,{endpointName:g,originalArgs:d}=T;return[g,d,E]}let B=(i,T,E)=>{let g=y(i);function d(a,n,r,o){let m=Q(E,n),F=Q(T.getState(),n);!m&&F&&c(a,o,n,T,r)}if(l.pending.match(i)){let[a,n,r]=A(i);d(a,g,r,n)}else if(w.match(i))for(let{queryDescription:a,value:n}of i.payload){let{endpointName:r,originalArgs:o,queryCacheKey:m}=a;d(r,m,i.meta.requestId,o),P(m,n,{})}else if(p.pending.match(i)){if(T.getState()[t].mutations[g]){let[n,r,o]=A(i);c(n,r,g,T,o)}}else if(D(i))P(g,i.payload,i.meta.baseQueryMeta);else if(R.match(i)||b.match(i))f(g);else if(e.util.resetApiState.match(i))for(let a of Object.keys(h))f(a)};function y(i){return M(i)?i.meta.arg.queryCacheKey:x(i)?i.meta.arg.fixedCacheKey??i.meta.requestId:R.match(i)?i.payload.queryCacheKey:b.match(i)?le(i.payload):""}function c(i,T,E,g,d){let a=J(u,i),n=a?.onCacheEntryAdded;if(!n)return;let r={},o=new Promise(I=>{r.cacheEntryRemoved=I}),m=Promise.race([new Promise(I=>{r.valueResolved=I}),o.then(()=>{throw Nt})]);m.catch(()=>{}),h[E]=r;let F=e.endpoints[i].select(Re(a)?T:E),C=g.dispatch((I,O,_)=>_),N={...g,getCacheEntry:()=>F(g.getState()),requestId:d,extra:C,updateCachedData:Re(a)?I=>g.dispatch(e.util.updateQueryData(i,T,I)):void 0,cacheDataLoaded:m,cacheEntryRemoved:o},v=n(T,N);Promise.resolve(v).catch(I=>{if(I!==Nt)throw I})}return B};var qt=({api:e,context:{apiUid:t},reducerPath:u})=>(l,p)=>{e.util.resetApiState.match(l)&&p.dispatch(e.internalActions.middlewareRegistered(t)),typeof process<"u"};var Kt=({reducerPath:e,context:t,context:{endpointDefinitions:u},mutationThunk:l,queryThunk:p,api:S,assertTagType:Q,refetchQuery:k,internalState:M})=>{let{removeQueryResult:x}=S.internalActions,D=(0,s.isAnyOf)((0,s.isFulfilled)(l),(0,s.isRejectedWithValue)(l)),h=(0,s.isAnyOf)((0,s.isFulfilled)(p,l),(0,s.isRejected)(p,l)),R=[],b=0,w=(A,B)=>{(p.pending.match(A)||l.pending.match(A))&&b++,h(A)&&(b=Math.max(0,b-1)),D(A)?f(Ue(A,"invalidatesTags",u,Q),B):h(A)?f([],B):S.util.invalidateTags.match(A)&&f(be(A.payload,void 0,void 0,void 0,void 0,Q),B)};function P(){return b>0}function f(A,B){let y=B.getState(),c=y[e];if(R.push(...A),c.config.invalidationBehavior==="delayed"&&P())return;let i=R;if(R=[],i.length===0)return;let T=S.util.selectInvalidatedBy(y,i);t.batch(()=>{let E=Array.from(T.values());for(let{queryCacheKey:g}of E){let d=c.queries[g],a=ye(M.currentSubscriptions,g,Ee);d&&(a.size===0?B.dispatch(x({queryCacheKey:g})):d.status!==W&&B.dispatch(k(d)))}})}return w};var Lt=({reducerPath:e,queryThunk:t,api:u,refetchQuery:l,internalState:p})=>{let{currentPolls:S,currentSubscriptions:Q}=p,k=new Set,M=null,x=(f,A)=>{(u.internalActions.updateSubscriptionOptions.match(f)||u.internalActions.unsubscribeQueryResult.match(f))&&D(f.payload.queryCacheKey,A),(t.pending.match(f)||t.rejected.match(f)&&f.meta.condition)&&D(f.meta.arg.queryCacheKey,A),(t.fulfilled.match(f)||t.rejected.match(f)&&!f.meta.condition)&&h(f.meta.arg,A),u.util.resetApiState.match(f)&&(w(),M&&(clearTimeout(M),M=null),k.clear())};function D(f,A){k.add(f),M||(M=setTimeout(()=>{for(let B of k)R({queryCacheKey:B},A);k.clear(),M=null},0))}function h({queryCacheKey:f},A){let B=A.getState()[e],y=B.queries[f],c=Q.get(f);if(!y||y.status===W)return;let{lowestPollingInterval:i,skipPollingIfUnfocused:T}=P(c);if(!Number.isFinite(i))return;let E=S.get(f);E?.timeout&&(clearTimeout(E.timeout),E.timeout=void 0);let g=Date.now()+i;S.set(f,{nextPollTimestamp:g,pollingInterval:i,timeout:setTimeout(()=>{(B.config.focused||!T)&&A.dispatch(l(y)),h({queryCacheKey:f},A)},i)})}function R({queryCacheKey:f},A){let y=A.getState()[e].queries[f],c=Q.get(f);if(!y||y.status===W)return;let{lowestPollingInterval:i}=P(c);if(!Number.isFinite(i)){b(f);return}let T=S.get(f),E=Date.now()+i;(!T||E<T.nextPollTimestamp)&&h({queryCacheKey:f},A)}function b(f){let A=S.get(f);A?.timeout&&clearTimeout(A.timeout),S.delete(f)}function w(){for(let f of S.keys())b(f)}function P(f=new Map){let A=!1,B=Number.POSITIVE_INFINITY;for(let y of f.values())y.pollingInterval&&(B=Math.min(y.pollingInterval,B),A=y.skipPollingIfUnfocused||A);return{lowestPollingInterval:B,skipPollingIfUnfocused:A}}return x};var _t=({api:e,context:t,queryThunk:u,mutationThunk:l})=>{let p=(0,s.isPending)(u,l),S=(0,s.isRejected)(u,l),Q=(0,s.isFulfilled)(u,l),k={};return(x,D)=>{if(p(x)){let{requestId:h,arg:{endpointName:R,originalArgs:b}}=x.meta,w=J(t,R),P=w?.onQueryStarted;if(P){let f={},A=new Promise((i,T)=>{f.resolve=i,f.reject=T});A.catch(()=>{}),k[h]=f;let B=e.endpoints[R].select(Re(w)?b:h),y=D.dispatch((i,T,E)=>E),c={...D,getCacheEntry:()=>B(D.getState()),requestId:h,extra:y,updateCachedData:Re(w)?i=>D.dispatch(e.util.updateQueryData(R,b,i)):void 0,queryFulfilled:A};P(b,c)}}else if(Q(x)){let{requestId:h,baseQueryMeta:R}=x.meta;k[h]?.resolve({data:x.payload,meta:R}),delete k[h]}else if(S(x)){let{requestId:h,rejectedWithValue:R,baseQueryMeta:b}=x.meta;k[h]?.reject({error:x.payload??x.error,isUnhandledError:!R,meta:b}),delete k[h]}}};var Ht=({reducerPath:e,context:t,api:u,refetchQuery:l,internalState:p})=>{let{removeQueryResult:S}=u.internalActions,Q=(M,x)=>{ie.match(M)&&k(x,"refetchOnFocus"),ae.match(M)&&k(x,"refetchOnReconnect")};function k(M,x){let D=M.getState()[e],h=D.queries,R=p.currentSubscriptions;t.batch(()=>{for(let b of R.keys()){let w=h[b],P=R.get(b);if(!P||!w)continue;let f=[...P.values()];(f.some(B=>B[x]===!0)||f.every(B=>B[x]===void 0)&&D.config[x])&&(P.size===0?M.dispatch(S({queryCacheKey:b})):w.status!==W&&M.dispatch(l(w)))}})}return Q};function Vt(e){let{reducerPath:t,queryThunk:u,api:l,context:p,getInternalState:S}=e,{apiUid:Q}=p,k={invalidateTags:(0,s.createAction)(`${t}/invalidateTags`)},M=R=>R.type.startsWith(`${t}/`),x=[qt,Ot,Kt,Lt,Ut,_t];return{middleware:R=>{let b=!1,w=S(R.dispatch),P={...e,internalState:w,refetchQuery:h,isThisApiSliceAction:M,mwApi:R},f=x.map(y=>y(P)),A=vt(P),B=Ht(P);return y=>c=>{if(!(0,s.isAction)(c))return y(c);b||(b=!0,R.dispatch(l.internalActions.middlewareRegistered(Q)));let i={...R,next:y},T=R.getState(),[E,g]=A(c,i,T),d;if(E?d=y(c):d=g,R.getState()[t]&&(B(c,i,T),M(c)||p.hasRehydrationInfo(c)))for(let a of f)a(c,i,T);return d}},actions:k};function h(R){return e.api.endpoints[R.endpointName].initiate(R.originalArgs,{subscribe:!1,forceRefetch:!0})}}var Me=Symbol(),_e=({createSelector:e=s.createSelector}={})=>({name:Me,init(t,{baseQuery:u,tagTypes:l,reducerPath:p,serializeQueryArgs:S,keepUnusedDataFor:Q,refetchOnMountOrArgChange:k,refetchOnFocus:M,refetchOnReconnect:x,invalidationBehavior:D,onSchemaFailure:h,catchSchemaFailure:R,skipSchemaValidation:b},w){(0,H.enablePatches)();let P=q=>(typeof process<"u",q);Object.assign(t,{reducerPath:p,endpoints:{},internalActions:{onOnline:ae,onOffline:he,onFocus:ie,onFocusLost:Te},util:{}});let f=Bt({serializeQueryArgs:S,reducerPath:p,createSelector:e}),{selectInvalidatedBy:A,selectCachedArgsForQuery:B,buildQuerySelector:y,buildInfiniteQuerySelector:c,buildMutationSelector:i}=f;X(t.util,{selectInvalidatedBy:A,selectCachedArgsForQuery:B});let{queryThunk:T,infiniteQueryThunk:E,mutationThunk:g,patchQueryData:d,updateQueryData:a,upsertQueryData:n,prefetch:r,buildMatchThunkActions:o}=xt({baseQuery:u,reducerPath:p,context:w,api:t,serializeQueryArgs:S,assertTagType:P,selectors:f,onSchemaFailure:h,catchSchemaFailure:R,skipSchemaValidation:b}),{reducer:m,actions:F}=Et({context:w,queryThunk:T,infiniteQueryThunk:E,mutationThunk:g,serializeQueryArgs:S,reducerPath:p,assertTagType:P,config:{refetchOnFocus:M,refetchOnReconnect:x,refetchOnMountOrArgChange:k,keepUnusedDataFor:Q,reducerPath:p,invalidationBehavior:D}});X(t.util,{patchQueryData:d,updateQueryData:a,upsertQueryData:n,prefetch:r,resetApiState:F.resetApiState,upsertQueryEntries:F.cacheEntriesUpserted}),X(t.internalActions,F);let C=new WeakMap,N=q=>ye(C,q,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:v,buildInitiateInfiniteQuery:I,buildInitiateMutation:O,getRunningMutationThunk:_,getRunningMutationsThunk:$,getRunningQueriesThunk:G,getRunningQueryThunk:V}=Rt({queryThunk:T,mutationThunk:g,infiniteQueryThunk:E,api:t,serializeQueryArgs:S,context:w,getInternalState:N});X(t.util,{getRunningMutationThunk:_,getRunningMutationsThunk:$,getRunningQueryThunk:V,getRunningQueriesThunk:G});let{middleware:z,actions:j}=Vt({reducerPath:p,context:w,queryThunk:T,mutationThunk:g,infiniteQueryThunk:E,api:t,assertTagType:P,selectors:f,getRunningQueryThunk:V,getInternalState:N});return X(t.util,j),X(t,{reducer:m,middleware:z}),{name:Me,injectEndpoint(q,K){let L=t,U=L.endpoints[q]??={};pe(K)&&X(U,{name:q,select:y(q,K),initiate:v(q,K)},o(T,q)),Tt(K)&&X(U,{name:q,select:i(),initiate:O(q)},o(g,q)),de(K)&&X(U,{name:q,select:c(q,K),initiate:I(q,K)},o(T,q))}}}});var jt=Le(_e());0&&(module.exports={NamedSchemaError,QueryStatus,_NEVER,buildCreateApi,copyWithStructuralSharing,coreModule,coreModuleName,createApi,defaultSerializeQueryArgs,fakeBaseQuery,fetchBaseQuery,retry,setupListeners,skipToken});
+//# sourceMappingURL=rtk-query.production.min.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.production.min.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/cjs/rtk-query.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/query/index.ts","../../../src/query/core/apiState.ts","../../../src/query/core/rtkImports.ts","../../../src/query/utils/copyWithStructuralSharing.ts","../../../src/query/utils/filterMap.ts","../../../src/query/utils/isAbsoluteUrl.ts","../../../src/query/utils/isDocumentVisible.ts","../../../src/query/utils/isNotNullish.ts","../../../src/query/utils/isOnline.ts","../../../src/query/utils/joinUrls.ts","../../../src/query/utils/getOrInsert.ts","../../../src/query/utils/signals.ts","../../../src/query/fetchBaseQuery.ts","../../../src/query/HandledError.ts","../../../src/query/retry.ts","../../../src/query/core/setupListeners.ts","../../../src/query/endpointDefinitions.ts","../../../src/query/utils/immerImports.ts","../../../src/query/core/buildInitiate.ts","../../../src/tsHelpers.ts","../../../src/query/apiTypes.ts","../../../src/query/standardSchema.ts","../../../src/query/core/buildThunks.ts","../../../src/query/utils/getCurrent.ts","../../../src/query/core/buildSlice.ts","../../../src/query/core/buildSelectors.ts","../../../src/query/createApi.ts","../../../src/query/defaultSerializeQueryArgs.ts","../../../src/query/fakeBaseQuery.ts","../../../src/query/tsHelpers.ts","../../../src/query/core/buildMiddleware/batchActions.ts","../../../src/query/core/buildMiddleware/cacheCollection.ts","../../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../../src/query/core/buildMiddleware/devMiddleware.ts","../../../src/query/core/buildMiddleware/invalidationByTags.ts","../../../src/query/core/buildMiddleware/polling.ts","../../../src/query/core/buildMiddleware/queryLifecycle.ts","../../../src/query/core/buildMiddleware/windowEventHandling.ts","../../../src/query/core/buildMiddleware/index.ts","../../../src/query/core/module.ts","../../../src/query/core/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport type { CombinedState, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './core/apiState';\nexport { QueryStatus } from './core/apiState';\nexport type { Api, ApiContext, Module } from './apiTypes';\nexport type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nexport 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';\nexport { fetchBaseQuery } from './fetchBaseQuery';\nexport type { FetchBaseQueryArgs, FetchBaseQueryError, FetchBaseQueryMeta, FetchArgs } from './fetchBaseQuery';\nexport { retry } from './retry';\nexport type { RetryOptions } from './retry';\nexport { setupListeners } from './core/setupListeners';\nexport { skipToken } from './core/buildSelectors';\nexport type { QueryResultSelectorResult, MutationResultSelectorResult, SkipToken } from './core/buildSelectors';\nexport type { QueryActionCreatorResult, MutationActionCreatorResult, StartQueryActionCreatorOptions } from './core/buildInitiate';\nexport type { CreateApi, CreateApiOptions } from './createApi';\nexport { buildCreateApi } from './createApi';\nexport { _NEVER, fakeBaseQuery } from './fakeBaseQuery';\nexport { copyWithStructuralSharing } from './utils/copyWithStructuralSharing';\nexport { createApi, coreModule, coreModuleName } from './core/index';\nexport type { InfiniteData, InfiniteQueryActionCreatorResult, InfiniteQueryConfigOptions, InfiniteQueryResultSelectorResult, InfiniteQuerySubState, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './core/index';\nexport type { ApiEndpointMutation, ApiEndpointQuery, ApiEndpointInfiniteQuery, ApiModules, CoreModule, PrefetchOptions } from './core/module';\nexport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nexport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nexport type { Id as TSHelpersId, NoInfer as TSHelpersNoInfer, Override as TSHelpersOverride } from './tsHelpers';\nexport { NamedSchemaError } from './standardSchema';","import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, FullTagDescription, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFromAnyQuery, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n  _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n  queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n  requestId: string;\n  fixedCacheKey?: string;\n} | {\n  requestId?: string;\n  fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number;\n  refetchOnReconnect: boolean;\n  refetchOnFocus: boolean;\n};\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam;\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (lastPage: DataType, allPages: Array<DataType>, lastPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>;\n  pageParams: Array<PageParam>;\n};\n\n// NOTE: DO NOT import and use this for runtime comparisons internally,\n// except in the RTKQ React package. Use the string versions just below this.\n// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated\n// constants like \"initialized\":\n// https://github.com/evanw/esbuild/releases/tag/v0.14.7\n// We still have to use this in the React package since we don't publicly export\n// the string constants below.\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\n\n// Use these string constants for runtime comparisons internally\nexport const STATUS_UNINITIALIZED = QueryStatus.uninitialized;\nexport const STATUS_PENDING = QueryStatus.pending;\nexport const STATUS_FULFILLED = QueryStatus.fulfilled;\nexport const STATUS_REJECTED = QueryStatus.rejected;\nexport type RequestStatusFlags = {\n  status: QueryStatus.uninitialized;\n  isUninitialized: true;\n  isLoading: false;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.pending;\n  isUninitialized: false;\n  isLoading: true;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.fulfilled;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: true;\n  isError: false;\n} | {\n  status: QueryStatus.rejected;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: false;\n  isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === STATUS_UNINITIALIZED,\n    isLoading: status === STATUS_PENDING,\n    isSuccess: status === STATUS_FULFILLED,\n    isError: status === STATUS_REJECTED\n  } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\nexport type SubscribersInternal = Map<string, SubscriptionOptions>;\nexport type Subscribers = {\n  [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>;\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string;\n  /**\n   * The received data from the query\n   */\n  data?: DataType;\n  /**\n   * The received error if applicable\n   */\n  error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string;\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number;\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n  error: undefined;\n}) | ({\n  status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n  status: QueryStatus.uninitialized;\n  originalArgs?: undefined;\n  data?: undefined;\n  error?: undefined;\n  requestId?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n  direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = {\n  requestId: string;\n  data?: ResultTypeFrom<D>;\n  error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  endpointName: string;\n  startedTimeStamp: number;\n  fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = (({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n  error: undefined;\n}) | (({\n  status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n  data?: undefined;\n}) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n  requestId?: undefined;\n  status: QueryStatus.uninitialized;\n  data?: undefined;\n  error?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n  queries: QueryState<D>;\n  mutations: MutationState<D>;\n  provided: InvalidationState<E>;\n  subscriptions: SubscriptionState;\n  config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = {\n  tags: { [_ in TagTypes]: {\n    [id: string]: Array<QueryCacheKey>;\n    [id: number]: Array<QueryCacheKey>;\n  } };\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;\n};\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionInternalState = Map<string, SubscribersInternal>;\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath;\n  online: boolean;\n  focused: boolean;\n  middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number;\n  invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from '@reduxjs/toolkit';","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n    return newObj;\n  }\n  const newKeys = Object.keys(newObj);\n  const oldKeys = Object.keys(oldObj);\n  let isSameObject = newKeys.length === oldKeys.length;\n  const mergeObj: any = Array.isArray(newObj) ? [] : {};\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n  }\n  return isSameObject ? oldObj : mergeObj;\n}","// Preserve type guard predicate behavior when passing to mapper\nexport 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[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[] {\n  return array.reduce<(U | U[])[]>((acc, item, i) => {\n    if (predicate(item as any, i)) {\n      acc.push(mapper(item as any, i));\n    }\n    return acc;\n  }, []).flat() as U[];\n}","/**\n * If either :// or // is present consider it to be an absolute url\n *\n * @param url string\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url);\n}","/**\n * Assumes true for a non-browser env, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true;\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null;\n}\nexport function filterNullishValues<T>(map?: Map<any, T>) {\n  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[];\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n  if (!base) {\n    return url!;\n  }\n  if (!url) {\n    return base;\n  }\n  if (isAbsoluteUrl(url)) {\n    return url;\n  }\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n  base = withoutTrailingSlash(base);\n  url = withoutLeadingSlash(url);\n  return `${base}${delimiter}${url}`;\n}","// Duplicate some of the utils in `/src/utils` to ensure\n// we don't end up dragging in larger chunks of the RTK core\n// into the RTKQ bundle\n\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport const createNewMap = () => new Map();","// AbortSignal.timeout() is currently baseline 2024\nexport const timeoutSignal = (milliseconds: number) => {\n  const abortController = new AbortController();\n  setTimeout(() => {\n    const message = 'signal timed out';\n    const name = 'TimeoutError';\n    abortController.abort(\n    // some environments (React Native, Node) don't have DOMException\n    typeof DOMException !== 'undefined' ? new DOMException(message, name) : Object.assign(new Error(message), {\n      name\n    }));\n  }, milliseconds);\n  return abortController.signal;\n};\n\n// AbortSignal.any() is currently baseline 2024\nexport const anySignal = (...signals: AbortSignal[]) => {\n  // if any are already aborted, return an already aborted signal\n  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);\n\n  // otherwise, create a new signal that aborts when any of the given signals abort\n  const abortController = new AbortController();\n  for (const signal of signals) {\n    signal.addEventListener('abort', () => abortController.abort(signal.reason), {\n      signal: abortController.signal,\n      once: true\n    });\n  }\n  return abortController.signal;\n};","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nimport { anySignal, timeoutSignal } from './utils/signals';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n  headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n  url: string;\n  params?: Record<string, any>;\n  body?: any;\n  responseHandler?: ResponseHandler;\n  validateStatus?: (response: Response, body: any) => boolean;\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n  /**\n   * * `number`:\n   *   HTTP status code\n   */\n  status: number;\n  data: unknown;\n} | {\n  /**\n   * * `\"FETCH_ERROR\"`:\n   *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n   **/\n  status: 'FETCH_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"PARSING_ERROR\"`:\n   *   An error happened during parsing.\n   *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n   *   or an error occurred while executing a custom `responseHandler`.\n   **/\n  status: 'PARSING_ERROR';\n  originalStatus: number;\n  data: string;\n  error: string;\n} | {\n  /**\n   * * `\"TIMEOUT_ERROR\"`:\n   *   Request timed out\n   **/\n  status: 'TIMEOUT_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"CUSTOM_ERROR\"`:\n   *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n   **/\n  status: 'CUSTOM_ERROR';\n  data?: unknown;\n  error: string;\n};\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj;\n  }\n  const copy: Record<string, any> = {\n    ...obj\n  };\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k];\n  }\n  return copy;\n}\n\n// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\nconst isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string;\n  prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n    arg: string | FetchArgs;\n    extraOptions: unknown;\n  }) => MaybePromise<Headers | void>;\n  fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n  paramsSerializer?: (params: Record<string, any>) => string;\n  /**\n   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean;\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string;\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n  request: Request;\n  response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = x => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n  }\n  return async (arg, api, extraOptions) => {\n    const {\n      getState,\n      extra,\n      endpoint,\n      forced,\n      type\n    } = api;\n    let meta: FetchBaseQueryMeta | undefined;\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? 'json' as const,\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? {\n      url: arg\n    } : arg;\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,\n      ...rest\n    };\n    headers = new Headers(stripUndefined(headers));\n    config.headers = (await prepareHeaders(headers, {\n      getState,\n      arg,\n      extra,\n      endpoint,\n      forced,\n      type,\n      extraOptions\n    })) || headers;\n    const bodyIsJsonifiable = isJsonifiable(config.body);\n\n    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically\n    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)\n    if (config.body != null && !bodyIsJsonifiable && typeof config.body !== 'string') {\n      config.headers.delete('content-type');\n    }\n    if (!config.headers.has('content-type') && bodyIsJsonifiable) {\n      config.headers.set('content-type', jsonContentType);\n    }\n    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer);\n    }\n\n    // Set Accept header based on responseHandler if not already set\n    if (!config.headers.has('accept')) {\n      if (responseHandler === 'json') {\n        config.headers.set('accept', 'application/json');\n      } else if (responseHandler === 'text') {\n        config.headers.set('accept', 'text/plain, text/html, */*');\n      }\n      // For 'content-type' responseHandler, don't set Accept (let server decide)\n    }\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?';\n      const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n      url += divider + query;\n    }\n    url = joinUrls(baseUrl, url);\n    const request = new Request(url, config);\n    const requestClone = new Request(url, config);\n    meta = {\n      request: requestClone\n    };\n    let response;\n    try {\n      response = await fetchFn(request);\n    } catch (e) {\n      return {\n        error: {\n          status: (e instanceof Error || typeof DOMException !== 'undefined' && e instanceof DOMException) && e.name === 'TimeoutError' ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n          error: String(e)\n        },\n        meta\n      };\n    }\n    const responseClone = response.clone();\n    meta.response = responseClone;\n    let resultData: any;\n    let responseText: string = '';\n    try {\n      let handleResponseError;\n      await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n      // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n      // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n      responseClone.text().then(r => responseText = r, () => {})]);\n      if (handleResponseError) throw handleResponseError;\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e)\n        },\n        meta\n      };\n    }\n    return validateStatus(response, resultData) ? {\n      data: resultData,\n      meta\n    } : {\n      error: {\n        status: response.status,\n        data: resultData\n      },\n      meta\n    };\n  };\n  async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response);\n    }\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n    }\n    if (responseHandler === 'json') {\n      const text = await response.text();\n      return text.length ? JSON.parse(text) : null;\n    }\n    return response.text();\n  }\n}","export class HandledError {\n  constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5, signal?: AbortSignal) {\n  const attempts = Math.min(attempt, maxRetries);\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n\n  await new Promise<void>((resolve, reject) => {\n    const timeoutId = setTimeout(() => resolve(), timeout);\n\n    // If signal is provided and gets aborted, clear timeout and reject\n    if (signal) {\n      const abortHandler = () => {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      };\n\n      // Check if already aborted\n      if (signal.aborted) {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      } else {\n        signal.addEventListener('abort', abortHandler, {\n          once: true\n        });\n      }\n    }\n  });\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n  attempt: number;\n  baseQueryApi: BaseQueryApi;\n  extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (attempt: number, maxRetries: number, signal?: AbortSignal) => Promise<void>;\n} & ({\n  /**\n   * How many times the query will be retried (default: 5)\n   */\n  maxRetries?: number;\n  retryCondition?: undefined;\n} | {\n  /**\n   * Callback to determine if a retry should be attempted.\n   * Return `true` for another retry and `false` to quit trying prematurely.\n   */\n  retryCondition?: RetryConditionFunction;\n  maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n  throw Object.assign(new HandledError({\n    error,\n    meta\n  }), {\n    throwImmediately: true\n  });\n}\n\n/**\n * Checks if the abort signal is aborted and fails immediately if so.\n * Used to exit retry loops cleanly when a request is aborted.\n */\nfunction failIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    fail({\n      status: 'CUSTOM_ERROR',\n      error: 'Aborted'\n    });\n  }\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n  const [maxRetries] = possibleMaxRetries.slice(-1);\n  const defaultRetryCondition: RetryConditionFunction = (_, __, {\n    attempt\n  }) => attempt <= maxRetries;\n  const options: {\n    maxRetries: number;\n    backoff: typeof defaultBackoff;\n    retryCondition: typeof defaultRetryCondition;\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions\n  };\n  let retry = 0;\n  while (true) {\n    // Check if aborted before each attempt\n    failIfAborted(api.signal);\n    try {\n      const result = await baseQuery(args, api, extraOptions);\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result);\n      }\n      return result;\n    } catch (e: any) {\n      retry++;\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value;\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e;\n      }\n      if (e instanceof HandledError) {\n        if (!options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n          attempt: retry,\n          baseQueryApi: api,\n          extraOptions\n        })) {\n          return e.value; // Max retries for expected error\n        }\n      } else {\n        // For unexpected errors, respect maxRetries\n        if (retry > options.maxRetries) {\n          // Return the error as a proper error response instead of throwing\n          return {\n            error: e\n          };\n        }\n      }\n\n      // Check if aborted before backoff\n      failIfAborted(api.signal);\n      try {\n        await options.backoff(retry, options.maxRetries, api.signal);\n      } catch (backoffError) {\n        // If backoff was aborted, exit the retry loop\n        failIfAborted(api.signal);\n        // Otherwise, rethrow the backoff error\n        throw backoffError;\n      }\n    }\n  }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n  fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const INTERNAL_PREFIX = '__rtkq/';\nconst ONLINE = 'online';\nconst OFFLINE = 'offline';\nconst FOCUS = 'focus';\nconst FOCUSED = 'focused';\nconst VISIBILITYCHANGE = 'visibilitychange';\nexport const onFocus = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${FOCUSED}`);\nexport const onFocusLost = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);\nexport const onOnline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${ONLINE}`);\nexport const onOffline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${OFFLINE}`);\nconst actions = {\n  onFocus,\n  onFocusLost,\n  onOnline,\n  onOffline\n};\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n}) => () => void) {\n  function defaultHandler() {\n    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map(action => () => dispatch(action()));\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus();\n      } else {\n        handleFocusLost();\n      }\n    };\n    let unsubscribe = () => {\n      initialized = false;\n    };\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        const handlers = {\n          [FOCUS]: handleFocus,\n          [VISIBILITYCHANGE]: handleVisibilityChange,\n          [ONLINE]: handleOnline,\n          [OFFLINE]: handleOffline\n        };\n        function updateListeners(add: boolean) {\n          Object.entries(handlers).forEach(([event, handler]) => {\n            if (add) {\n              window.addEventListener(event, handler, false);\n            } else {\n              window.removeEventListener(event, handler);\n            }\n          });\n        }\n        // Handle focus events\n        updateListeners(true);\n        initialized = true;\n        unsubscribe = () => {\n          updateListeners(false);\n          initialized = false;\n        };\n      }\n    }\n    return unsubscribe;\n  }\n  return customHandler ? customHandler(dispatch, actions) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from 'immer';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { ENDPOINT_QUERY, isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { filterNullishValues } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n  [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\ntype RefetchOptions = {\n  refetchCachedPages?: boolean;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection;\n  param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>, InfiniteQueryArgFrom<D>>>, 'initialPageParam' | 'refetchCachedPages'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n  requestId: string;\n  subscriptionOptions: SubscriptionOptions | undefined;\n  abort(): void;\n  unsubscribe(): void;\n  updateSubscriptionOptions(options: SubscriptionOptions): void;\n  queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n  arg: any;\n  unwrap(): Promise<any>;\n  refetch(options?: RefetchOptions): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: QueryArgFrom<D>;\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: InfiniteQueryArgFrom<D>;\n  unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n  refetch(options?: Pick<StartInfiniteQueryActionCreatorOptions<D>, 'refetchCachedPages'>): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n  fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n  data: ResultTypeFrom<D>;\n  error?: undefined;\n} | {\n  data?: undefined;\n  error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string;\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>;\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean;\n    fixedCacheKey?: string;\n  };\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string;\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void;\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void;\n};\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context,\n  getInternalState\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  api: Api<any, EndpointDefinitions, any, any>;\n  context: ApiContext<EndpointDefinitions>;\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState;\n}) {\n  const getRunningQueries = (dispatch: Dispatch) => getInternalState(dispatch)?.runningQueries;\n  const getRunningMutations = (dispatch: Dispatch) => getInternalState(dispatch)?.runningMutations;\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions\n  } = api.internalActions;\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk\n  };\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      return getRunningQueries(dispatch)?.get(queryCacheKey) as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningMutationThunk(\n  /**\n   * this is only here to allow TS to infer the result type by input value\n   * we could use it to validate the result, but it's probably not necessary\n   */\n  _endpointName: string, fixedCacheKeyOrRequestId: string) {\n    return (dispatch: Dispatch) => {\n      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as MutationActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningQueries(dispatch));\n  }\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningMutations(dispatch));\n  }\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return;\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      (middlewareWarning as any).triggered = true;\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n        // Otherwise, must not have been added\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n      }\n    }\n  }\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n    const queryAction: AnyQueryActionCreator<any> = (arg, {\n      subscribe = true,\n      forceRefetch,\n      subscriptionOptions,\n      [forceQueryFnSymbol]: forceQueryFn,\n      ...rest\n    } = {}) => (dispatch, getState) => {\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName\n      });\n      let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n      const commonThunkArgs = {\n        ...rest,\n        type: ENDPOINT_QUERY as 'query',\n        subscribe,\n        forceRefetch: forceRefetch,\n        subscriptionOptions,\n        endpointName,\n        originalArgs: arg,\n        queryCacheKey,\n        [forceQueryFnSymbol]: forceQueryFn\n      };\n      if (isQueryDefinition(endpointDefinition)) {\n        thunk = queryThunk(commonThunkArgs);\n      } else {\n        const {\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam' | 'refetchCachedPages'>;\n        thunk = infiniteQueryThunk({\n          ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n          // Supply these even if undefined. This helps with a field existence\n          // check over in `buildSlice.ts`\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        });\n      }\n      const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n      const thunkResult = dispatch(thunk);\n      const stateAfter = selector(getState());\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort\n      } = thunkResult;\n      const skippedSynchronously = stateAfter.requestId !== requestId;\n      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);\n      const selectFromState = () => selector(getState());\n      const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n      // a query has been forced (upsertQueryData)\n      // -> we want to resolve it once data has been written with the data that will be written\n      thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n      // a query has been skipped due to a condition and we do not have any currently running query\n      // -> we want to resolve it immediately with the current data\n      Promise.resolve(stateAfter) :\n      // query just started or one is already in flight\n      // -> wait for the running query, then resolve with data from after that\n      Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n        arg,\n        requestId,\n        subscriptionOptions,\n        queryCacheKey,\n        abort,\n        async unwrap() {\n          const result = await statePromise;\n          if (result.isError) {\n            throw result.error;\n          }\n          return result.data;\n        },\n        refetch: (options?: RefetchOptions) => dispatch(queryAction(arg, {\n          subscribe: false,\n          forceRefetch: true,\n          ...options\n        })),\n        unsubscribe() {\n          if (subscribe) dispatch(unsubscribeQueryResult({\n            queryCacheKey,\n            requestId\n          }));\n        },\n        updateSubscriptionOptions(options: SubscriptionOptions) {\n          statePromise.subscriptionOptions = options;\n          dispatch(updateSubscriptionOptions({\n            endpointName,\n            requestId,\n            queryCacheKey,\n            options\n          }));\n        }\n      });\n      if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n        const runningQueries = getRunningQueries(dispatch)!;\n        runningQueries.set(queryCacheKey, statePromise);\n        statePromise.then(() => {\n          runningQueries.delete(queryCacheKey);\n        });\n      }\n      return statePromise;\n    };\n    return queryAction;\n  }\n  function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return queryAction;\n  }\n  function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return infiniteQueryAction;\n  }\n  function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n    return (arg, {\n      track = true,\n      fixedCacheKey\n    } = {}) => (dispatch, getState) => {\n      const thunk = mutationThunk({\n        type: 'mutation',\n        endpointName,\n        originalArgs: arg,\n        track,\n        fixedCacheKey\n      });\n      const thunkResult = dispatch(thunk);\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort,\n        unwrap\n      } = thunkResult;\n      const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n        data\n      })), error => ({\n        error\n      }));\n      const reset = () => {\n        dispatch(removeMutationResult({\n          requestId,\n          fixedCacheKey\n        }));\n      };\n      const ret = Object.assign(returnValuePromise, {\n        arg: thunkResult.arg,\n        requestId,\n        abort,\n        unwrap,\n        reset\n      });\n      const runningMutations = getRunningMutations(dispatch)!;\n      runningMutations.set(requestId, ret);\n      ret.then(() => {\n        runningMutations.delete(requestId);\n      });\n      if (fixedCacheKey) {\n        runningMutations.set(fixedCacheKey, ret);\n        ret.then(() => {\n          if (runningMutations.get(fixedCacheKey) === ret) {\n            runningMutations.delete(fixedCacheKey);\n          }\n        });\n      }\n      return ret;\n    };\n  }\n}","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn } from './baseQueryTypes';\nimport type { CombinedState, CoreModule, QueryKeys } from './core';\nimport type { ApiModules } from './core/module';\nimport type { CreateApiOptions } from './createApi';\nimport type { EndpointBuilder, EndpointDefinition, EndpointDefinitions, UpdateDefinitions } from './endpointDefinitions';\nimport type { NoInfer, UnionToIntersection, WithRequiredProp } from './tsHelpers';\nexport type ModuleName = keyof ApiModules<any, any, any, any>;\nexport type Module<Name extends ModuleName> = {\n  name: Name;\n  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>): {\n    injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;\n  };\n};\nexport interface ApiContext<Definitions extends EndpointDefinitions> {\n  apiUid: string;\n  endpointDefinitions: Definitions;\n  batch(cb: () => void): void;\n  extractRehydrationInfo: (action: UnknownAction) => CombinedState<any, any, any> | undefined;\n  hasRehydrationInfo: (action: UnknownAction) => boolean;\n}\nexport const getEndpointDefinition = <Definitions extends EndpointDefinitions, EndpointName extends keyof Definitions>(context: ApiContext<Definitions>, endpointName: EndpointName) => context.endpointDefinitions[endpointName];\nexport 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]> & {\n  /**\n   * 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.\n   */\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\n    endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;\n    /**\n     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n     *\n     * If set to `true`, will override existing endpoints with the new definition.\n     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n     */\n    overrideExisting?: boolean | 'throw';\n  }): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;\n  /**\n   *A function to enhance a generated API with additional information. Useful with code-generation.\n   */\n  enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {\n    addTagTypes?: readonly NewTagTypes[];\n    endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? { [K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void) } : never;\n  }): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;\n};","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { SchemaError } from '@standard-schema/utils';\nimport type { SchemaType } from './endpointDefinitions';\nexport class NamedSchemaError extends SchemaError {\n  constructor(issues: readonly StandardSchemaV1.Issue[], public readonly value: any, public readonly schemaName: `${SchemaType}Schema`, public readonly _bqMeta: any) {\n    super(issues);\n  }\n}\nexport const shouldSkip = (skipSchemaValidation: boolean | SchemaType[] | undefined, schemaName: SchemaType) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(schema: Schema, data: unknown, schemaName: `${SchemaType}Schema`, bqMeta: any): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data);\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);\n  }\n  return result.value;\n}","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from '../utils/immerImports';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultDescription, ResultTypeFrom, SchemaFailureConverter, SchemaFailureHandler, SchemaFailureInfo, SchemaType } from '../endpointDefinitions';\nimport { calculateProvidedBy, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nimport { parseWithSchema, NamedSchemaError, shouldSkip } from '../standardSchema';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>;\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n  type: 'query';\n  originalArgs: unknown;\n  endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n  type: `query`;\n  originalArgs: unknown;\n  endpointName: string;\n  param: unknown;\n  direction?: InfiniteQueryDirection;\n  refetchCachedPages?: boolean;\n};\ntype MutationThunkArg = {\n  type: 'mutation';\n  originalArgs: unknown;\n  endpointName: string;\n  track?: boolean;\n  fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n  pendingMeta: {\n    startedTimeStamp: number;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  fulfilledMeta: {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  rejectedMeta: {\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;\nexport type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;\nexport type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;\nexport type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;\nexport type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[];\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[];\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n  [SHOULD_AUTOBATCH]: true;\n} => {\n  return {\n    ...arg,\n    [SHOULD_AUTOBATCH]: true\n  };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n  reducerPath,\n  baseQuery,\n  context: {\n    endpointDefinitions\n  },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation\n}: {\n  baseQuery: BaseQuery;\n  reducerPath: ReducerPath;\n  context: ApiContext<Definitions>;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  api: Api<BaseQuery, Definitions, ReducerPath, any>;\n  assertTagType: AssertTagTypes;\n  selectors: AllSelectors;\n  onSchemaFailure: SchemaFailureHandler | undefined;\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined;\n  skipSchemaValidation: boolean | SchemaType[] | undefined;\n}) {\n  type State = RootState<any, string, ReducerPath>;\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n    const endpointDefinition = endpointDefinitions[endpointName];\n    const queryCacheKey = serializeQueryArgs({\n      queryArgs: arg,\n      endpointDefinition,\n      endpointName\n    });\n    dispatch(api.internalActions.queryResultPatched({\n      queryCacheKey,\n      patches\n    }));\n    if (!updateProvided) {\n      return;\n    }\n    const newValue = api.endpoints[endpointName].select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n    dispatch(api.internalActions.updateProvidedBy([{\n      queryCacheKey,\n      providedTags\n    }]));\n  };\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items];\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n  }\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item];\n    return max && newItems.length > max ? newItems.slice(1) : newItems;\n  }\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n    const endpointDefinition = api.endpoints[endpointName];\n    const currentState = endpointDefinition.select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const ret: PatchCollection = {\n      patches: [],\n      inversePatches: [],\n      undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n    };\n    if (currentState.status === STATUS_UNINITIALIZED) {\n      return ret;\n    }\n    let newValue;\n    if ('data' in currentState) {\n      if (isDraftable(currentState.data)) {\n        const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n        ret.patches.push(...patches);\n        ret.inversePatches.push(...inversePatches);\n        newValue = value;\n      } else {\n        newValue = updateRecipe(currentState.data);\n        ret.patches.push({\n          op: 'replace',\n          path: [],\n          value: newValue\n        });\n        ret.inversePatches.push({\n          op: 'replace',\n          path: [],\n          value: currentState.data\n        });\n      }\n    }\n    if (ret.patches.length === 0) {\n      return ret;\n    }\n    dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n    return ret;\n  };\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n    type EndpointName = typeof endpointName;\n    const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n      subscribe: false,\n      forceRefetch: true,\n      [forceQueryFnSymbol]: () => ({\n        data: value\n      })\n    })) as UpsertThunkResult<Definitions, EndpointName>;\n    return res;\n  };\n  const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n  };\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }> = async (arg, {\n    signal,\n    abort,\n    rejectWithValue,\n    fulfillWithValue,\n    dispatch,\n    getState,\n    extra\n  }) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName];\n    const {\n      metaSchema,\n      skipSchemaValidation = globalSkipSchemaValidation\n    } = endpointDefinition;\n    const isQuery = arg.type === ENDPOINT_QUERY;\n    try {\n      let transformResponse: TransformCallback = defaultTransformResponse;\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n      };\n      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined;\n      let finalQueryReturnValue: QueryReturnValue;\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({\n            data\n          });\n        }\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param\n        };\n        const pageResponse = await executeRequest(finalQueryArg);\n        const addTo = previous ? addToStart : addToEnd;\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages)\n          },\n          meta: pageResponse.meta\n        };\n      };\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n        let result: QueryReturnValue;\n        const {\n          extraOptions,\n          argSchema,\n          rawResponseSchema,\n          responseSchema\n        } = endpointDefinition;\n        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {\n          finalQueryArg = await parseWithSchema(argSchema, finalQueryArg, 'argSchema', {} // we don't have a meta yet, so we can't pass it\n          );\n        }\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn();\n        } else if (endpointDefinition.query) {\n          // We should only run `transformResponse` when the endpoint has a `query` method,\n          // and we're not doing an `upsertQueryData`.\n          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n          result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n        } else {\n          result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n          let err: undefined | string;\n          if (!result) {\n            err = `${what} did not return anything.`;\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`;\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`;\n                break;\n              }\n            }\n          }\n          if (err) {\n            console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`, result);\n          }\n        }\n        if (result.error) throw new HandledError(result.error, result.meta);\n        let {\n          data\n        } = result;\n        if (rawResponseSchema && !shouldSkip(skipSchemaValidation, 'rawResponse')) {\n          data = await parseWithSchema(rawResponseSchema, result.data, 'rawResponseSchema', result.meta);\n        }\n        let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);\n        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {\n          transformedResponse = await parseWithSchema(responseSchema, transformedResponse, 'responseSchema', result.meta);\n        }\n        return {\n          ...result,\n          data: transformedResponse\n        };\n      }\n      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const {\n          infiniteQueryOptions\n        } = endpointDefinition;\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const {\n          maxPages = Infinity\n        } = infiniteQueryOptions;\n\n        // Priority: per-call override > endpoint config > default (true)\n        const refetchCachedPages = (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;\n        let result: QueryReturnValue;\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = {\n          pages: [],\n          pageParams: []\n        };\n        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch =\n        // arg.forceRefetch\n        isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n        const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward';\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n          const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);\n          result = await fetchPage(existingData, param, maxPages, previous);\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const {\n            initialPageParam = infiniteQueryOptions.initialPageParam\n          } = arg as InfiniteQueryThunkArg<any>;\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? [];\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n          const totalPages = cachedPageParams.length;\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages);\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n            } as QueryReturnValue;\n          }\n          if (refetchCachedPages) {\n            // Fetch remaining pages\n            for (let i = 1; i < totalPages; i++) {\n              const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>, arg.originalArgs);\n              result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n            }\n          }\n        }\n        finalQueryReturnValue = result;\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs);\n      }\n      if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta') && finalQueryReturnValue.meta) {\n        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, 'metaSchema', finalQueryReturnValue.meta);\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n        fulfilledTimeStamp: Date.now(),\n        baseQueryMeta: finalQueryReturnValue.meta\n      }));\n    } catch (error) {\n      let caughtError = error;\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n        const {\n          rawErrorResponseSchema,\n          errorResponseSchema\n        } = endpointDefinition;\n        let {\n          value,\n          meta\n        } = caughtError;\n        try {\n          if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, 'rawErrorResponse')) {\n            value = await parseWithSchema(rawErrorResponseSchema, value, 'rawErrorResponseSchema', meta);\n          }\n          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta);\n          }\n          let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);\n          if (errorResponseSchema && !shouldSkip(skipSchemaValidation, 'errorResponse')) {\n            transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, 'errorResponseSchema', meta);\n          }\n          return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({\n            baseQueryMeta: meta\n          }));\n        } catch (e) {\n          caughtError = e;\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n          };\n          endpointDefinition.onSchemaFailure?.(caughtError, info);\n          onSchemaFailure?.(caughtError, info);\n          const {\n            catchSchemaFailure = globalCatchSchemaFailure\n          } = endpointDefinition;\n          if (catchSchemaFailure) {\n            return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({\n              baseQueryMeta: caughtError._bqMeta\n            }));\n          }\n        }\n      } catch (e) {\n        caughtError = e;\n      }\n      if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n        console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, caughtError);\n      } else {\n        console.error(caughtError);\n      }\n      throw caughtError;\n    }\n  };\n  function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n    const fulfilledVal = requestState?.fulfilledTimeStamp;\n    const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n    }\n    return false;\n  }\n  const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n    const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n      state: RootState<any, string, ReducerPath>;\n    }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({\n        arg\n      }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName];\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n            direction: (arg as InfiniteQueryThunkArg<any>).direction\n          } : {})\n        });\n      },\n      condition(queryThunkArg, {\n        getState\n      }) {\n        const state = getState();\n        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n        const fulfilledVal = requestState?.fulfilledTimeStamp;\n        const currentArg = queryThunkArg.originalArgs;\n        const previousArg = requestState?.originalArgs;\n        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true;\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false;\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true;\n        }\n        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n          currentArg,\n          previousArg,\n          endpointState: requestState,\n          state\n        })) {\n          return true;\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false;\n        }\n        return true;\n      },\n      dispatchConditionRejection: true\n    });\n    return generatedQueryThunk;\n  };\n  const queryThunk = createQueryThunk<QueryThunkArg>();\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n  const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({\n        startedTimeStamp: Date.now()\n      });\n    }\n  });\n  const hasTheForce = (options: any): options is {\n    force: boolean;\n  } => 'force' in options;\n  const hasMaxAge = (options: any): options is {\n    ifOlderThan: false | number;\n  } => 'ifOlderThan' in options;\n  const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions = {}): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n    const force = hasTheForce(options) && options.force;\n    const maxAge = hasMaxAge(options) && options.ifOlderThan;\n    const queryAction = (force: boolean = true) => {\n      const options: StartQueryActionCreatorOptions = {\n        forceRefetch: force,\n        subscribe: false\n      };\n      return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n    };\n    const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n    if (force) {\n      dispatch(queryAction());\n    } else if (maxAge) {\n      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n      if (!lastFulfilledTs) {\n        dispatch(queryAction());\n        return;\n      }\n      const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n      if (shouldRetrigger) {\n        dispatch(queryAction());\n      }\n    } else {\n      // If prefetching with no options, just let it try\n      dispatch(queryAction(false));\n    }\n  };\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n  }\n  function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n    } as Matchers<Thunk, any>;\n  }\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions\n  };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  const lastIndex = pages.length - 1;\n  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n  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);\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../utils/immerImports';\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}","import type { PayloadAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { STATUS_FULFILLED, STATUS_PENDING, QueryStatus, STATUS_REJECTED, STATUS_UNINITIALIZED } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { ENDPOINT_QUERY, isInfiniteQueryDefinition, type AssertTagTypes, type EndpointDefinitions, type FullTagDescription, type QueryDefinition } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { applyPatches, original, isDraft } from '../utils/immerImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport { getCurrent } from '../utils/getCurrent';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n  endpointName: EndpointName;\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string;\n  arg: unknown;\n  value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg;\n  value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n  const substate = state[queryCacheKey];\n  if (substate) {\n    update(substate);\n  }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n} | MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}, update: (substate: MutationSubState<any>) => void) {\n  const substate = state[getMutationCacheKey(id)];\n  if (substate) {\n    update(substate);\n  }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo\n  },\n  assertTagType,\n  config\n}: {\n  reducerPath: string;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  context: ApiContext<EndpointDefinitions>;\n  assertTagType: AssertTagTypes;\n  config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`);\n  function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n    // requestStatus: 'pending'\n  } & {\n    startedTimeStamp: number;\n  }) {\n    draft[arg.queryCacheKey] ??= {\n      status: STATUS_UNINITIALIZED,\n      endpointName: arg.endpointName\n    };\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n      substate.status = STATUS_PENDING;\n      substate.requestId = upserting && substate.requestId ?\n      // for `upsertQuery` **updates**, keep the current `requestId`\n      substate.requestId :\n      // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n      meta.requestId;\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs;\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp;\n      const endpointDefinition = definitions[meta.arg.endpointName];\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;\n        (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n      }\n    });\n  }\n  function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n  } & {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n  }, payload: unknown, upserting: boolean) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n      if (substate.requestId !== meta.requestId && !upserting) return;\n      const {\n        merge\n      } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n      substate.status = STATUS_FULFILLED;\n      if (merge) {\n        if (substate.data !== undefined) {\n          const {\n            fulfilledTimeStamp,\n            arg,\n            baseQueryMeta,\n            requestId\n          } = meta;\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, draftSubstateData => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId\n            });\n          });\n          substate.data = newData;\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload;\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n      }\n      delete substate.error;\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n    });\n  }\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey\n          }\n        }: PayloadAction<QuerySubstateIdentifier>) {\n          delete draft[queryCacheKey];\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n      },\n      cacheEntriesUpserted: {\n        reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n          RTK_autoBatch: boolean;\n          requestId: string;\n          timestamp: number;\n        }>) {\n          for (const entry of action.payload) {\n            const {\n              queryDescription: arg,\n              value\n            } = entry;\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp\n            });\n            writeFulfilledCacheEntry(draft, {\n              arg,\n              requestId: action.meta.requestId,\n              fulfilledTimeStamp: action.meta.timestamp,\n              baseQueryMeta: {}\n            }, value,\n            // We know we're upserting here\n            true);\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n            const {\n              endpointName,\n              arg,\n              value\n            } = entry;\n            const endpointDefinition = definitions[endpointName];\n            const queryDescription: QueryThunkArg = {\n              type: ENDPOINT_QUERY as 'query',\n              endpointName,\n              originalArgs: entry.arg,\n              queryCacheKey: serializeQueryArgs({\n                queryArgs: arg,\n                endpointDefinition,\n                endpointName\n              })\n            };\n            return {\n              queryDescription,\n              value\n            };\n          });\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now()\n            }\n          };\n          return result;\n        }\n      },\n      queryResultPatched: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey,\n            patches\n          }\n        }: PayloadAction<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n            substate.data = applyPatches(substate.data as any, patches.concat());\n          });\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(queryThunk.pending, (draft, {\n        meta,\n        meta: {\n          arg\n        }\n      }) => {\n        const upserting = isUpsertQuery(arg);\n        writePendingCacheEntry(draft, arg, upserting, meta);\n      }).addCase(queryThunk.fulfilled, (draft, {\n        meta,\n        payload\n      }) => {\n        const upserting = isUpsertQuery(meta.arg);\n        writeFulfilledCacheEntry(draft, meta, payload, upserting);\n      }).addCase(queryThunk.rejected, (draft, {\n        meta: {\n          condition,\n          arg,\n          requestId\n        },\n        error,\n        payload\n      }) => {\n        updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n          if (condition) {\n            // request was aborted due to condition (another query already running)\n          } else {\n            // request failed\n            if (substate.requestId !== requestId) return;\n            substate.status = STATUS_REJECTED;\n            substate.error = (payload ?? error) as any;\n          }\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          queries\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(queries)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, {\n          payload\n        }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload);\n          if (cacheKey in draft) {\n            delete draft[cacheKey];\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(mutationThunk.pending, (draft, {\n        meta,\n        meta: {\n          requestId,\n          arg,\n          startedTimeStamp\n        }\n      }) => {\n        if (!arg.track) return;\n        draft[getMutationCacheKey(meta)] = {\n          requestId,\n          status: STATUS_PENDING,\n          endpointName: arg.endpointName,\n          startedTimeStamp\n        };\n      }).addCase(mutationThunk.fulfilled, (draft, {\n        payload,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_FULFILLED;\n          substate.data = payload;\n          substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n        });\n      }).addCase(mutationThunk.rejected, (draft, {\n        payload,\n        error,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_REJECTED;\n          substate.error = (payload ?? error) as any;\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          mutations\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(mutations)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) &&\n          // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n          key !== entry?.requestId) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  type CalculateProvidedByAction = UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>;\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {}\n  };\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(draft, action: PayloadAction<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>) {\n          for (const {\n            queryCacheKey,\n            providedTags\n          } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey);\n            for (const {\n              type,\n              id\n            } of providedTags) {\n              const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] = providedTags as FullTagDescription<string>[];\n          }\n        },\n        prepare: prepareAutoBatched<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n        payload: {\n          queryCacheKey\n        }\n      }) => {\n        removeCacheKeyFromTags(draft, queryCacheKey);\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          provided\n        } = extractRehydrationInfo(action)!;\n        for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {\n          for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n            const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n            for (const queryCacheKey of cacheKeys) {\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n              draft.keys[queryCacheKey] = provided.keys[queryCacheKey];\n            }\n          }\n        }\n      }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n        writeProvidedTagsForQueries(draft, [action]);\n      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {\n        const mockActions: CalculateProvidedByAction[] = action.payload.map(({\n          queryDescription,\n          value\n        }) => {\n          return {\n            type: 'UNKNOWN',\n            payload: value,\n            meta: {\n              requestStatus: 'fulfilled',\n              requestId: 'UNKNOWN',\n              arg: queryDescription\n            }\n          };\n        });\n        writeProvidedTagsForQueries(draft, mockActions);\n      });\n    }\n  });\n  function removeCacheKeyFromTags(draft: InvalidationState<any>, queryCacheKey: QueryCacheKey) {\n    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type;\n      const tagId = tag.id ?? '__internal_without_id';\n      const tagSubscriptions = draft.tags[tagType]?.[tagId];\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(qc => qc !== queryCacheKey);\n      }\n    }\n    delete draft.keys[queryCacheKey];\n  }\n  function writeProvidedTagsForQueries(draft: InvalidationState<string>, actions: CalculateProvidedByAction[]) {\n    const providedByEntries = actions.map(action => {\n      const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n      const {\n        queryCacheKey\n      } = action.meta.arg;\n      return {\n        queryCacheKey,\n        providedTags\n      };\n    });\n    invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(d, a: PayloadAction<{\n        endpointName: string;\n        requestId: string;\n        options: Subscribers[number];\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      unsubscribeQueryResult(d, a: PayloadAction<{\n        requestId: string;\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {}\n    }\n  });\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload);\n        },\n        prepare: prepareAutoBatched<Patch[]>()\n      }\n    }\n  });\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, {\n        payload\n      }: PayloadAction<string>) {\n        state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n      }\n    },\n    extraReducers: builder => {\n      builder.addCase(onOnline, state => {\n        state.online = true;\n      }).addCase(onOffline, state => {\n        state.online = false;\n      }).addCase(onFocus, state => {\n        state.focused = true;\n      }).addCase(onFocusLost, state => {\n        state.focused = false;\n      })\n      // update the state to be a new object to be picked up as a \"state change\"\n      // by redux-persist's `autoMergeLevel2`\n      .addMatcher(hasRehydrationInfo, draft => ({\n        ...draft\n      }));\n    }\n  });\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer\n  });\n  const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState\n  };\n  return {\n    reducer,\n    actions\n  };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { filterMap, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState, QueryStatus } from './apiState';\nimport { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { type AllQueryKeys, getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n  isFetchNextPageError: boolean;\n  isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n  requestId: string | undefined;\n  fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n  status: STATUS_UNINITIALIZED\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  reducerPath: ReducerPath;\n  createSelector: typeof _createSelector;\n}) {\n  type RootState = _RootState<Definitions, string, string>;\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig\n  };\n  function withRequestFlags<T extends {\n    status: QueryStatus;\n  }>(substate: T): T & RequestStatusFlags {\n    return {\n      ...substate,\n      ...getRequestStatusFlags(substate.status)\n    };\n  }\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath];\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state;\n        (selectApiState as any).triggered = true;\n        console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n      }\n    }\n    return state;\n  }\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries;\n  }\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey];\n  }\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations;\n  }\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config;\n  }\n  function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n    status: QueryStatus;\n  }>(substate: T) => T & RequestStatusFlags) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner);\n      }\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n      return createSelector(selectQuerySubstate, combiner);\n    };\n  }\n  function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n  }\n  function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const {\n      infiniteQueryOptions\n    } = endpointDefinition;\n    function withInfiniteQueryResultFlags<T extends {\n      status: QueryStatus;\n    }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status)\n      };\n      const {\n        isLoading,\n        isError,\n        direction\n      } = stateWithRequestFlags;\n      const isForward = direction === 'forward';\n      const isBackward = direction === 'backward';\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward\n      };\n    }\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n  }\n  function buildMutationSelector() {\n    return (id => {\n      let mutationId: string | typeof skipToken;\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken;\n      } else {\n        mutationId = id;\n      }\n      const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n      return createSelector(finalSelectMutationSubstate, withRequestFlags);\n    }) as MutationResultSelectorFactory<any, RootState>;\n  }\n  function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n    endpointName: string;\n    originalArgs: any;\n    queryCacheKey: QueryCacheKey;\n  }> {\n    const apiState = state[reducerPath];\n    const toInvalidate = new Set<QueryCacheKey>();\n    const finalTags = filterMap(tags, isNotNullish, expandTagDescription);\n    for (const tag of finalTags) {\n      const provided = apiState.provided.tags[tag.type];\n      if (!provided) {\n        continue;\n      }\n      let invalidateSubscriptions = (tag.id !== undefined ?\n      // id given: invalidate all queries that provide this type & id\n      provided[tag.id] :\n      // no id: invalidate all queries that provide this type\n      Object.values(provided).flat()) ?? [];\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate);\n      }\n    }\n    return Array.from(toInvalidate.values()).flatMap(queryCacheKey => {\n      const querySubState = apiState.queries[queryCacheKey];\n      return querySubState ? {\n        queryCacheKey,\n        endpointName: querySubState.endpointName!,\n        originalArgs: querySubState.originalArgs\n      } : [];\n    });\n  }\n  function selectCachedArgsForQuery<QueryName extends AllQueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return filterMap(Object.values(selectQueries(state) as QueryState<any>), (entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n      status: QueryStatus.uninitialized;\n    }> => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, entry => entry.originalArgs);\n  }\n  function getHasNextPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data) return false;\n    return getNextPageParam(options, data, queryArg) != null;\n  }\n  function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data || !options.getPreviousPageParam) return false;\n    return getPreviousPageParam(options, data, queryArg) != null;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport { getEndpointDefinition, type Api, type ApiContext, type Module, type ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions, SchemaFailureConverter, SchemaFailureHandler, SchemaType } from './endpointDefinitions';\nimport { DefinitionType, ENDPOINT_INFINITEQUERY, ENDPOINT_MUTATION, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n  /**\n   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery;\n  /**\n   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[];\n  /**\n   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath;\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>;\n  /**\n   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n   */\n  endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n  /**\n   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts'\n   *     })\n   *   }),\n   *   // highlight-start\n   *   keepUnusedDataFor: 5\n   *   // highlight-end\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately';\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (action: UnknownAction, {\n    reducerPath\n  }: {\n    reducerPath: ReducerPath;\n  }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n      reducerPath: (options.reducerPath ?? 'api') as any\n    }));\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n          finalSerializeQueryArgs = queryArgsApi => {\n            const initialResult = endpointSQA(queryArgsApi);\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult;\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult\n              });\n            }\n          };\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs;\n        }\n        return finalSerializeQueryArgs(queryArgsApi);\n      },\n      tagTypes: [...(options.tagTypes || [])]\n    };\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn();\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n    };\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({\n        addTagTypes,\n        endpoints\n      }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;\n              (optionsWithDefaults.tagTypes as any[]).push(eT);\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(getEndpointDefinition(context, endpointName));\n            } else {\n              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);\n            }\n          }\n        }\n        return api;\n      }\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n    const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n    function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: x => ({\n          ...x,\n          type: ENDPOINT_QUERY\n        }) as any,\n        mutation: x => ({\n          ...x,\n          type: ENDPOINT_MUTATION\n        }) as any,\n        infiniteQuery: x => ({\n          ...x,\n          type: ENDPOINT_INFINITEQUERY\n        }) as any\n      });\n      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n            console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          }\n          continue;\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          if (isInfiniteQueryDefinition(definition)) {\n            const {\n              infiniteQueryOptions\n            } = definition;\n            const {\n              maxPages,\n              getPreviousPageParam\n            } = infiniteQueryOptions;\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n              }\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n              }\n            }\n          }\n        }\n        context.endpointDefinitions[endpointName] = definition;\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition);\n        }\n      }\n      return api as any;\n    }\n    return api.injectEndpoints({\n      endpoints: options.endpoints as any\n    });\n  };\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs\n}) => {\n  let serialized = '';\n  const cached = cache?.get(queryArgs);\n  if (typeof cached === 'string') {\n    serialized = cached;\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? {\n        $bigint: value.toString()\n      } : value;\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n        acc[key] = (value as any)[key];\n        return acc;\n      }, {}) : value;\n      return value;\n    });\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified);\n    }\n    serialized = stringified;\n  }\n  return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n  return function () {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n  };\n}","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionInternalState, SubscriptionState } from '../apiState';\nimport { produceWithPatches } from '../../utils/immerImports';\nimport type { Action } from '@reduxjs/toolkit';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n  api,\n  queryThunk,\n  internalState,\n  mwApi\n}) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n  let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n  const {\n    updateSubscriptionOptions,\n    unsubscribeQueryResult\n  } = api.internalActions;\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (currentSubscriptions: SubscriptionInternalState, action: Action) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const {\n        queryCacheKey,\n        requestId,\n        options\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub?.has(requestId)) {\n        sub.set(requestId, options);\n      }\n      return true;\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const {\n        queryCacheKey,\n        requestId\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub) {\n        sub.delete(requestId);\n      }\n      return true;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      currentSubscriptions.delete(action.payload.queryCacheKey);\n      return true;\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: {\n          arg,\n          requestId\n        }\n      } = action;\n      const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n      if (arg.subscribe) {\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n      }\n      return true;\n    }\n    let mutated = false;\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: {\n          condition,\n          arg,\n          requestId\n        }\n      } = action;\n      if (condition && arg.subscribe) {\n        const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n        mutated = true;\n      }\n    }\n    return mutated;\n  };\n  const getSubscriptions = () => internalState.currentSubscriptions;\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions();\n    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);\n    return subscriptionsForQueryArg?.size ?? 0;\n  };\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions();\n    return !!subscriptions?.get(queryCacheKey)?.get(requestId);\n  };\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed\n  };\n  function serializeSubscriptions(currentSubscriptions: SubscriptionInternalState): SubscriptionState {\n    // We now use nested Maps for subscriptions, instead of\n    // plain Records. Stringify this accordingly so we can\n    // convert it to the shape we need for the store.\n    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));\n  }\n  return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);\n    }\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = {};\n      internalState.currentSubscriptions.clear();\n      updateSyncTimer = null;\n      return [true, false];\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors];\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n    let actionShouldContinue = true;\n\n    // HACK Sneak the test-only polling state back out\n    if (process.env.NODE_ENV === 'test' && typeof action.type === 'string' && action.type === `${api.reducerPath}/getPolling`) {\n      return [false, internalState.currentPolls] as any;\n    }\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = serializeSubscriptions(internalState.currentSubscriptions);\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions;\n          updateSyncTimer = null;\n        }, 500);\n      }\n      const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n    }\n    return [actionShouldContinue, false];\n  };\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\n\n/**\n * @example\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => 'posts',\n *       // highlight-start\n *       keepUnusedDataFor: 5\n *       // highlight-end\n *     })\n *   })\n * })\n * ```\n */\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   */\n  keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectConfig\n  },\n  getRunningQueryThunk,\n  mwApi\n}) => {\n  const {\n    removeQueryResult,\n    unsubscribeQueryResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);\n    if (!subscriptions) {\n      return false;\n    }\n    const hasSubscriptions = subscriptions.size > 0;\n    return hasSubscriptions;\n  }\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n  function abortAllPromises<T extends {\n    abort?: () => void;\n  }>(promiseMap: Map<string, T | undefined>): void {\n    for (const promise of promiseMap.values()) {\n      promise?.abort?.();\n    }\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    const state = mwApi.getState();\n    const config = selectConfig(state);\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[];\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n      } else {\n        const {\n          queryCacheKey\n        } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n        queryCacheKeys = [queryCacheKey];\n      }\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n    }\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout);\n        delete currentRemovalTimeouts[key];\n      }\n      abortAllPromises(internalState.runningQueries);\n      abortAllPromises(internalState.runningMutations);\n    }\n    if (context.hasRehydrationInfo(action)) {\n      const {\n        queries\n      } = context.extractRehydrationInfo(action)!;\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n    }\n  };\n  function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n    const state = api.getState();\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey);\n      if (entry?.endpointName) {\n        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config);\n      }\n    }\n  }\n  function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string, api: SubMiddlewareApi, config: ConfigState<string>) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName) as QueryDefinition<any, any, any, any>;\n    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return;\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n      if (currentTimeout) {\n        clearTimeout(currentTimeout);\n      }\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          // Try to abort any running query for this cache key\n          const entry = selectQueryEntry(api.getState(), queryCacheKey);\n          if (entry?.endpointName) {\n            const runningQuery = api.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));\n            runningQuery?.abort();\n          }\n          api.dispatch(removeQueryResult({\n            queryCacheKey\n          }));\n        }\n        delete currentRemovalTimeouts![queryCacheKey];\n      }, finalKeepUnusedDataFor * 1000);\n    }\n  }\n  return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta, BaseQueryResult } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition, DefinitionType } from '../../endpointDefinitions';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nimport { getEndpointDefinition } from '@internal/query/apiTypes';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<{\n    type: DefinitionType.query;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<{\n    type: DefinitionType.mutation;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>;\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>;\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown;\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: MetaType;\n  }, typeof neverResolvedError>;\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectApiState\n  }\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk);\n  const isMutationThunk = isAsyncThunkAction(mutationThunk);\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    valueResolved?(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    cacheEntryRemoved(): void;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const {\n    removeQueryResult,\n    removeMutationResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta\n      });\n      delete lifecycle.valueResolved;\n    }\n  }\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey];\n      lifecycle.cacheEntryRemoved();\n    }\n  }\n  function getActionMetaFields(action: ReturnType<typeof queryThunk.pending> | ReturnType<typeof mutationThunk.pending>) {\n    const {\n      arg,\n      requestId\n    } = action.meta;\n    const {\n      endpointName,\n      originalArgs\n    } = arg;\n    return [endpointName, originalArgs, requestId] as const;\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey;\n    function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    }\n    if (queryThunk.pending.match(action)) {\n      const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);\n    } else if (cacheEntriesUpserted.match(action)) {\n      for (const {\n        queryDescription,\n        value\n      } of action.payload) {\n        const {\n          endpointName,\n          originalArgs,\n          queryCacheKey\n        } = queryDescription;\n        checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n        resolveLifecycleEntry(queryCacheKey, value, {});\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n      if (state) {\n        const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n    } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {\n      removeLifecycleEntry(cacheKey);\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey);\n      }\n    }\n  };\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n    }\n    if (removeQueryResult.match(action)) return action.payload.queryCacheKey;\n    if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n    return '';\n  }\n  function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName);\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n    if (!onCacheEntryAdded) return;\n    const lifecycle = {} as CacheLifecycle;\n    const cacheEntryRemoved = new Promise<void>(resolve => {\n      lifecycle.cacheEntryRemoved = resolve;\n    });\n    const cacheDataLoaded: PromiseWithKnownReason<{\n      data: unknown;\n      meta: unknown;\n    }, typeof neverResolvedError> = Promise.race([new Promise<{\n      data: unknown;\n      meta: unknown;\n    }>(resolve => {\n      lifecycle.valueResolved = resolve;\n    }), cacheEntryRemoved.then(() => {\n      throw neverResolvedError;\n    })]);\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {});\n    lifecycleMap[queryCacheKey] = lifecycle;\n    const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);\n    const extra = mwApi.dispatch((_, __, extra) => extra);\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n      cacheDataLoaded,\n      cacheEntryRemoved\n    };\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch(e => {\n      if (e === neverResolvedError) return;\n      throw e;\n    });\n  }\n  return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: {\n    apiUid\n  },\n  reducerPath\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n      }\n    }\n  };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler } from './types';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: {\n    endpointDefinitions\n  },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));\n  let pendingTagInvalidations: FullTagDescription<string>[] = [];\n  // Track via counter so we can avoid iterating over state every time\n  let pendingRequestCount = 0;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {\n      pendingRequestCount++;\n    }\n    if (isQueryEnd(action)) {\n      pendingRequestCount = Math.max(0, pendingRequestCount - 1);\n    }\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi);\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n    }\n  };\n  function hasPendingRequests() {\n    return pendingRequestCount > 0;\n  }\n  function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n    const rootState = mwApi.getState();\n    const state = rootState[reducerPath];\n    pendingTagInvalidations.push(...newTags);\n    if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests()) {\n      return;\n    }\n    const tags = pendingTagInvalidations;\n    pendingTagInvalidations = [];\n    if (tags.length === 0) return;\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values());\n      for (const {\n        queryCacheKey\n      } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey];\n        const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);\n        if (querySubState) {\n          if (subscriptionSubState.size === 0) {\n            mwApi.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            mwApi.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers, SubscribersInternal } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    currentPolls,\n    currentSubscriptions\n  } = internalState;\n\n  // Batching state for polling updates\n  const pendingPollingUpdates = new Set<string>();\n  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n      schedulePollingUpdate(action.payload.queryCacheKey, mwApi);\n    }\n    if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);\n    }\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n      startNextPoll(action.meta.arg, mwApi);\n    }\n    if (api.util.resetApiState.match(action)) {\n      clearPolls();\n      // Clear any pending updates\n      if (pollingUpdateTimer) {\n        clearTimeout(pollingUpdateTimer);\n        pollingUpdateTimer = null;\n      }\n      pendingPollingUpdates.clear();\n    }\n  };\n  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {\n    pendingPollingUpdates.add(queryCacheKey);\n    if (!pollingUpdateTimer) {\n      pollingUpdateTimer = setTimeout(() => {\n        // Process all pending updates in a single batch\n        for (const key of pendingPollingUpdates) {\n          updatePollingInterval({\n            queryCacheKey: key as any\n          }, api);\n        }\n        pendingPollingUpdates.clear();\n        pollingUpdateTimer = null;\n      }, 0);\n    }\n  }\n  function startNextPoll({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;\n    const {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) return;\n    const currentPoll = currentPolls.get(queryCacheKey);\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout);\n      currentPoll.timeout = undefined;\n    }\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    currentPolls.set(queryCacheKey, {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState));\n        }\n        startNextPoll({\n          queryCacheKey\n        }, api);\n      }, lowestPollingInterval)\n    });\n  }\n  function updatePollingInterval({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {\n      return;\n    }\n    const {\n      lowestPollingInterval\n    } = findLowestPollingInterval(subscriptions);\n\n    // HACK add extra data to track how many times this has been called in tests\n    // yes we're mutating a nonexistent field on a Map here\n    if (process.env.NODE_ENV === 'test') {\n      const updateCounters = (currentPolls as any).pollUpdateCounters ??= {};\n      updateCounters[queryCacheKey] ??= 0;\n      updateCounters[queryCacheKey]++;\n    }\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey);\n      return;\n    }\n    const currentPoll = currentPolls.get(queryCacheKey);\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({\n        queryCacheKey\n      }, api);\n    }\n  }\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls.get(key);\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout);\n    }\n    currentPolls.delete(key);\n  }\n  function clearPolls() {\n    for (const key of currentPolls.keys()) {\n      cleanupPollForKey(key);\n    }\n  }\n  function findLowestPollingInterval(subscribers: SubscribersInternal = new Map()) {\n    let skipPollingIfUnfocused: boolean | undefined = false;\n    let lowestPollingInterval = Number.POSITIVE_INFINITY;\n    for (const entry of subscribers.values()) {\n      if (!!entry.pollingInterval) {\n        lowestPollingInterval = Math.min(entry.pollingInterval!, lowestPollingInterval);\n        skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;\n      }\n    }\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    };\n  }\n  return handler;\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: BaseQueryMeta<BaseQuery>;\n  }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n  error: BaseQueryError<BaseQuery>;\n  /**\n   * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n   */\n  isUnhandledError: false;\n  /**\n   * The `meta` returned by the `baseQuery`\n   */\n  meta: BaseQueryMeta<BaseQuery>;\n} | {\n  error: unknown;\n  meta?: undefined;\n  /**\n   * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n   * There can not be made any assumption about the shape of `error`.\n   */\n  isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * import { messageCreated } from './notificationsSlice\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'))\n   *         try {\n   *           const { data } = await queryFulfilled\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'))\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'))\n   *         }\n   *       }\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk);\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    resolve(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    reject(value: QueryFulfilledRejectionReason<any>): unknown;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: {\n          endpointName,\n          originalArgs\n        }\n      } = action.meta;\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const onQueryStarted = endpointDefinition?.onQueryStarted;\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle;\n        const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n          data: unknown;\n          meta: unknown;\n        }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n          lifecycle.resolve = resolve;\n          lifecycle.reject = reject;\n        });\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {});\n        lifecycleMap[requestId] = lifecycle;\n        const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);\n        const extra = mwApi.dispatch((_, __, extra) => extra);\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n          queryFulfilled\n        };\n        onQueryStarted(originalArgs, lifecycleApi as any);\n      }\n    } else if (isFullfilledThunk(action)) {\n      const {\n        requestId,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta\n      });\n      delete lifecycleMap[requestId];\n    } else if (isRejectedThunk(action)) {\n      const {\n        requestId,\n        rejectedWithValue,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any\n      });\n      delete lifecycleMap[requestId];\n    }\n  };\n  return handler;\n};","import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus');\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect');\n    }\n  };\n  function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n    const state = api.getState()[reducerPath];\n    const queries = state.queries;\n    const subscriptions = internalState.currentSubscriptions;\n    context.batch(() => {\n      for (const queryCacheKey of subscriptions.keys()) {\n        const querySubState = queries[queryCacheKey];\n        const subscriptionSubState = subscriptions.get(queryCacheKey);\n        if (!subscriptionSubState || !querySubState) continue;\n        const values = [...subscriptionSubState.values()];\n        const shouldRefetch = values.some(sub => sub[type] === true) || values.every(sub => sub[type] === undefined) && state.config[type];\n        if (shouldRefetch) {\n          if (subscriptionSubState.size === 0) {\n            api.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            api.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const {\n    reducerPath,\n    queryThunk,\n    api,\n    context,\n    getInternalState\n  } = input;\n  const {\n    apiUid\n  } = context;\n  const actions = {\n    invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n  };\n  const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n  const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n  const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n    let initialized = false;\n    const internalState = getInternalState(mwApi.dispatch);\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction,\n      mwApi\n    };\n    const handlers = handlerBuilders.map(build => build(builderArgs));\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n    const windowEventsHandler = buildWindowEventHandler(builderArgs);\n    return next => {\n      return action => {\n        if (!isAction(action)) {\n          return next(action);\n        }\n        if (!initialized) {\n          initialized = true;\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n        }\n        const mwApiWithNext = {\n          ...mwApi,\n          next\n        };\n        const stateBefore = mwApi.getState();\n        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n        let res: any;\n        if (actionShouldContinue) {\n          res = next(action);\n        } else {\n          res = internalProbeResult;\n        }\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore);\n          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore);\n            }\n          }\n        }\n        return res;\n      };\n    };\n  };\n  return {\n    middleware,\n    actions\n  };\n  function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n    status: QueryStatus.uninitialized;\n  }>) {\n    return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true\n    });\n  }\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Dispatch, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from '../utils/immerImports';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nimport { getOrInsertComputed } from '../utils';\nimport type { CreateSelectorFunction } from 'reselect';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n */\nexport type PrefetchOptions = {\n  ifOlderThan?: false | number;\n} | {\n  force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath;\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions;\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n    /**\n     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'query';\n      }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'infinitequery';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n        type: 'mutation';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n       *\n       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n      /**\n       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n       *\n       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n       *\n       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n       *\n       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n       *\n       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n      /**\n       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n       *\n       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n       *\n       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState'];\n      upsertQueryEntries: UpsertEntries<Definitions>;\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n       *\n       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n       *\n       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n        endpointName: string;\n        originalArgs: any;\n        queryCacheKey: string;\n      }>;\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;\n    };\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never };\n  };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(api, {\n    baseQuery,\n    tagTypes,\n    reducerPath,\n    serializeQueryArgs,\n    keepUnusedDataFor,\n    refetchOnMountOrArgChange,\n    refetchOnFocus,\n    refetchOnReconnect,\n    invalidationBehavior,\n    onSchemaFailure,\n    catchSchemaFailure,\n    skipSchemaValidation\n  }, context) {\n    enablePatches();\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n    const assertTagType: AssertTagTypes = tag => {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n        }\n      }\n      return tag;\n    };\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost\n      },\n      util: {}\n    });\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector\n    });\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector\n    } = selectors;\n    safeAssign(api.util, {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery\n    });\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation\n    });\n    const {\n      reducer,\n      actions: sliceActions\n    } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior\n      }\n    });\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n    });\n    safeAssign(api.internalActions, sliceActions);\n    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>();\n    const getInternalState = (dispatch: Dispatch) => {\n      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({\n        currentSubscriptions: new Map(),\n        currentPolls: new Map(),\n        runningQueries: new Map(),\n        runningMutations: new Map()\n      }));\n      return state;\n    };\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context,\n      getInternalState\n    });\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk\n    });\n    const {\n      middleware,\n      actions: middlewareActions\n    } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors,\n      getRunningQueryThunk,\n      getInternalState\n    });\n    safeAssign(api.util, middlewareActions);\n    safeAssign(api, {\n      reducer: reducer as any,\n      middleware\n    });\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n        const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n        if (isQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildQuerySelector(endpointName, definition),\n            initiate: buildInitiateQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildMutationSelector(),\n            initiate: buildInitiateMutation(endpointName)\n          }, buildMatchThunkActions(mutationThunk, endpointName));\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildInfiniteQuerySelector(endpointName, definition),\n            initiate: buildInitiateInfiniteQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n      }\n    };\n  }\n});","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,GAAA,gBAAAC,GAAA,WAAAC,GAAA,mBAAAC,GAAA,8BAAAC,GAAA,eAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,8BAAAC,GAAA,kBAAAC,GAAA,mBAAAC,GAAA,UAAAC,GAAA,mBAAAC,GAAA,cAAAC,KAAA,eAAAC,GAAAhB,ICkEO,IAAKiB,QACVA,EAAA,cAAgB,gBAChBA,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WAJDA,QAAA,IAQCC,EAAuB,gBACvBC,GAAiB,UACjBC,GAAmB,YACnBC,GAAkB,WA0BxB,SAASC,GAAsBC,EAAyC,CAC7E,MAAO,CACL,OAAAA,EACA,gBAAiBA,IAAWL,EAC5B,UAAWK,IAAWJ,GACtB,UAAWI,IAAWH,GACtB,QAASG,IAAWF,EACtB,CACF,CC3GA,IAAAG,EAAoR,4BCDpR,IAAMC,GAAqC,gBAEpC,SAASC,GAA0BC,EAAaC,EAAkB,CACvE,GAAID,IAAWC,GAAU,EAAEH,GAAcE,CAAM,GAAKF,GAAcG,CAAM,GAAK,MAAM,QAAQD,CAA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AqBJ,CAAU,GACjC7B,EAAW+B,EAAU,CACnB,KAAMH,EACN,OAAQ7B,EAAsB,EAC9B,SAAUoB,EAAsBS,CAAY,CAC9C,EAAGpB,EAAuBL,EAAeyB,CAAY,CAAC,EAEpDM,GAA0BL,CAAU,GACtC7B,EAAW+B,EAAU,CACnB,KAAMH,EACN,OAAQ9B,EAA2B8B,EAAcC,CAAU,EAC3D,SAAUX,EAA2BU,EAAcC,CAAU,CAC/D,EAAGrB,EAAuBP,EAAY2B,CAAY,CAAC,CAEvD,CACF,CACF,CACF,GCniBO,IAAMO,GAA2BC,GAAeC,GAAW,CAAC","names":["query_exports","__export","NamedSchemaError","QueryStatus","_NEVER","buildCreateApi","copyWithStructuralSharing","coreModule","coreModuleName","createApi","defaultSerializeQueryArgs","fakeBaseQuery","fetchBaseQuery","retry","setupListeners","skipToken","__toCommonJS","QueryStatus","STATUS_UNINITIALIZED","STATUS_PENDING","STATUS_FULFILLED","STATUS_REJECTED","getRequestStatusFlags","status","import_toolkit","isPlainObject","copyWithStructuralSharing","oldObj","newObj","newKeys","oldKeys","isSameObject","mergeObj","key","filterMap","array","predicate","mapper","acc","item","i","isAbsoluteUrl","url","isDocumentVisible","isNotNullish","v","filterNullishValues","map","isOnline","withoutTrailingSlash","url","withoutLeadingSlash","joinUrls","base","isAbsoluteUrl","delimiter","getOrInsertComputed","map","key","compute","createNewMap","timeoutSignal","milliseconds","abortController","message","name","anySignal","signals","signal","defaultFetchFn","args","defaultValidateStatus","response","defaultIsJsonContentType","headers","stripUndefined","obj","copy","k","v","isJsonifiable","body","fetchBaseQuery","baseUrl","prepareHeaders","x","fetchFn","paramsSerializer","isJsonContentType","jsonContentType","jsonReplacer","defaultTimeout","globalResponseHandler","globalValidateStatus","baseFetchOptions","arg","api","extraOptions","getState","extra","endpoint","forced","type","meta","url","params","responseHandler","validateStatus","timeout","rest","config","anySignal","timeoutSignal","bodyIsJsonifiable","divider","query","joinUrls","request","e","responseClone","resultData","responseText","handleResponseError","handleResponse","r","text","HandledError","value","meta","defaultBackoff","attempt","maxRetries","signal","attempts","timeout","resolve","reject","timeoutId","abortHandler","fail","error","meta","HandledError","failIfAborted","EMPTY_OPTIONS","retryWithBackoff","baseQuery","defaultOptions","args","api","extraOptions","possibleMaxRetries","x","options","_","__","retry","result","e","backoffError","INTERNAL_PREFIX","ONLINE","OFFLINE","FOCUS","FOCUSED","VISIBILITYCHANGE","onFocus","onFocusLost","onOnline","onOffline","actions","initialized","setupListeners","dispatch","customHandler","defaultHandler","handleFocus","handleFocusLost","handleOnline","handleOffline","action","handleVisibilityChange","unsubscribe","updateListeners","add","handlers","event","handler","ENDPOINT_QUERY","ENDPOINT_MUTATION","ENDPOINT_INFINITEQUERY","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","isAnyQueryDefinition","calculateProvidedBy","description","result","error","queryArg","meta","assertTagTypes","finalDescription","isFunction","filterMap","isNotNullish","tag","expandTagDescription","t","import_immer","import_toolkit","asSafePromise","promise","fallback","getEndpointDefinition","context","endpointName","forceQueryFnSymbol","isUpsertQuery","arg","buildInitiate","serializeQueryArgs","queryThunk","infiniteQueryThunk","mutationThunk","api","context","getInternalState","getRunningQueries","dispatch","getRunningMutations","unsubscribeQueryResult","removeMutationResult","updateSubscriptionOptions","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningQueryThunk","getRunningMutationThunk","getRunningQueriesThunk","getRunningMutationsThunk","endpointName","queryArgs","endpointDefinition","getEndpointDefinition","queryCacheKey","_endpointName","fixedCacheKeyOrRequestId","filterNullishValues","middlewareWarning","buildInitiateAnyQuery","queryAction","subscribe","forceRefetch","subscriptionOptions","forceQueryFn","rest","getState","thunk","commonThunkArgs","ENDPOINT_QUERY","isQueryDefinition","direction","initialPageParam","refetchCachedPages","selector","thunkResult","stateAfter","requestId","abort","skippedSynchronously","runningQuery","selectFromState","statePromise","result","options","runningQueries","track","fixedCacheKey","unwrap","returnValuePromise","asSafePromise","data","error","reset","ret","runningMutations","import_utils","NamedSchemaError","issues","value","schemaName","_bqMeta","shouldSkip","skipSchemaValidation","parseWithSchema","schema","data","bqMeta","result","defaultTransformResponse","baseQueryReturnValue","addShouldAutoBatch","arg","buildThunks","reducerPath","baseQuery","endpointDefinitions","serializeQueryArgs","api","assertTagType","selectors","onSchemaFailure","globalCatchSchemaFailure","globalSkipSchemaValidation","patchQueryData","endpointName","patches","updateProvided","dispatch","getState","endpointDefinition","queryCacheKey","newValue","providedTags","calculateProvidedBy","addToStart","items","item","max","newItems","addToEnd","updateQueryData","updateRecipe","currentState","ret","STATUS_UNINITIALIZED","value","inversePatches","upsertQueryData","forceQueryFnSymbol","getTransformCallbackForEndpoint","transformFieldName","executeEndpoint","signal","abort","rejectWithValue","fulfillWithValue","extra","metaSchema","skipSchemaValidation","isQuery","ENDPOINT_QUERY","transformResponse","baseQueryApi","isForcedQuery","forceQueryFn","finalQueryReturnValue","fetchPage","data","param","maxPages","previous","finalQueryArg","pageResponse","executeRequest","addTo","result","extraOptions","argSchema","rawResponseSchema","responseSchema","shouldSkip","parseWithSchema","HandledError","transformedResponse","infiniteQueryOptions","refetchCachedPages","blankData","cachedData","existingData","getPreviousPageParam","getNextPageParam","initialPageParam","cachedPageParams","firstPageParam","totalPages","i","error","caughtError","transformErrorResponse","rawErrorResponseSchema","errorResponseSchema","meta","transformedErrorResponse","e","NamedSchemaError","info","catchSchemaFailure","state","requestState","baseFetchOnMountOrArgChange","fulfilledVal","refetchVal","createQueryThunk","isInfiniteQueryDefinition","queryThunkArg","currentArg","previousArg","direction","isUpsertQuery","isQueryDefinition","queryThunk","infiniteQueryThunk","mutationThunk","hasTheForce","options","hasMaxAge","prefetch","force","maxAge","queryAction","latestStateValue","lastFulfilledTs","matchesEndpoint","action","buildMatchThunkActions","thunk","pages","pageParams","queryArg","lastIndex","calculateProvidedByThunk","type","getCurrent","value","updateQuerySubstateIfExists","state","queryCacheKey","update","substate","getMutationCacheKey","id","updateMutationSubstateIfExists","initialState","buildSlice","reducerPath","queryThunk","mutationThunk","serializeQueryArgs","definitions","apiUid","extractRehydrationInfo","hasRehydrationInfo","assertTagType","config","resetApiState","writePendingCacheEntry","draft","arg","upserting","meta","STATUS_UNINITIALIZED","STATUS_PENDING","endpointDefinition","isInfiniteQueryDefinition","writeFulfilledCacheEntry","payload","merge","STATUS_FULFILLED","fulfilledTimeStamp","baseQueryMeta","requestId","newData","draftSubstateData","copyWithStructuralSharing","querySlice","action","entry","value","endpointName","ENDPOINT_QUERY","patches","builder","isUpsertQuery","condition","error","STATUS_REJECTED","queries","key","mutationSlice","cacheKey","startedTimeStamp","mutations","initialInvalidationState","invalidationSlice","providedTags","removeCacheKeyFromTags","type","subscribedQueries","provided","incomingTags","cacheKeys","writeProvidedTagsForQueries","mockActions","queryDescription","existingTags","getCurrent","tag","tagType","tagId","tagSubscriptions","qc","actions","providedByEntries","calculateProvidedByThunk","subscriptionSlice","internalSubscriptionsSlice","configSlice","isOnline","isDocumentVisible","onOnline","onOffline","onFocus","onFocusLost","combinedReducer","reducer","skipToken","initialSubState","STATUS_UNINITIALIZED","defaultQuerySubState","defaultMutationSubState","buildSelectors","serializeQueryArgs","reducerPath","createSelector","selectSkippedQuery","state","selectSkippedMutation","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","selectInvalidatedBy","selectCachedArgsForQuery","selectApiState","selectQueries","selectMutations","selectQueryEntry","selectConfig","withRequestFlags","substate","getRequestStatusFlags","rootState","cacheKey","buildAnyQuerySelector","endpointName","endpointDefinition","combiner","queryArgs","serializedArgs","infiniteQueryOptions","withInfiniteQueryResultFlags","stateWithRequestFlags","isLoading","isError","direction","isForward","isBackward","getHasNextPage","getHasPreviousPage","id","mutationId","getMutationCacheKey","tags","apiState","toInvalidate","finalTags","filterMap","isNotNullish","expandTagDescription","tag","provided","invalidateSubscriptions","invalidate","queryCacheKey","querySubState","queryName","entry","options","data","queryArg","getNextPageParam","getPreviousPageParam","import_toolkit","cache","defaultSerializeQueryArgs","endpointName","queryArgs","serialized","cached","stringified","key","value","acc","import_reselect","buildCreateApi","modules","options","extractRehydrationInfo","action","optionsWithDefaults","queryArgsApi","finalSerializeQueryArgs","defaultSerializeQueryArgs","endpointSQA","initialResult","context","fn","api","injectEndpoints","addTagTypes","endpoints","eT","endpointName","partialDefinition","getEndpointDefinition","initializedModules","m","inject","evaluatedEndpoints","x","ENDPOINT_QUERY","ENDPOINT_MUTATION","ENDPOINT_INFINITEQUERY","definition","_formatProdErrorMessage","import_toolkit","_NEVER","fakeBaseQuery","_formatProdErrorMessage","safeAssign","target","args","buildBatchedActionsHandler","api","queryThunk","internalState","mwApi","subscriptionsPrefix","previousSubscriptions","updateSyncTimer","updateSubscriptionOptions","unsubscribeQueryResult","actuallyMutateSubscriptions","currentSubscriptions","action","queryCacheKey","requestId","options","sub","arg","substate","getOrInsertComputed","createNewMap","mutated","condition","getSubscriptions","subscriptionSelectors","serializeSubscriptions","k","v","didMutate","actionShouldContinue","newSubscriptions","patches","isSubscriptionSliceAction","isAdditionalSubscriptionAction","THIRTY_TWO_BIT_MAX_TIMER_SECONDS","buildCacheCollectionHandler","reducerPath","api","queryThunk","context","internalState","selectQueryEntry","selectConfig","getRunningQueryThunk","mwApi","removeQueryResult","unsubscribeQueryResult","cacheEntriesUpserted","canTriggerUnsubscribe","anySubscriptionsRemainingForKey","queryCacheKey","subscriptions","currentRemovalTimeouts","abortAllPromises","promiseMap","promise","handler","action","state","config","queryCacheKeys","entry","handleUnsubscribeMany","key","timeout","queries","cacheKeys","handleUnsubscribe","endpointName","keepUnusedDataFor","getEndpointDefinition","finalKeepUnusedDataFor","currentTimeout","neverResolvedError","buildCacheLifecycleHandler","api","reducerPath","context","queryThunk","mutationThunk","internalState","selectQueryEntry","selectApiState","isQueryThunk","isMutationThunk","isFulfilledThunk","lifecycleMap","removeQueryResult","removeMutationResult","cacheEntriesUpserted","resolveLifecycleEntry","cacheKey","data","meta","lifecycle","removeLifecycleEntry","getActionMetaFields","action","arg","requestId","endpointName","originalArgs","handler","mwApi","stateBefore","getCacheKey","checkForNewCacheKey","oldEntry","newEntry","handleNewKey","queryDescription","value","queryCacheKey","getMutationCacheKey","endpointDefinition","getEndpointDefinition","onCacheEntryAdded","cacheEntryRemoved","resolve","cacheDataLoaded","selector","isAnyQueryDefinition","extra","_","__","lifecycleApi","updateRecipe","runningHandler","e","buildDevCheckHandler","api","apiUid","reducerPath","action","mwApi","buildInvalidationByTagsHandler","reducerPath","context","endpointDefinitions","mutationThunk","queryThunk","api","assertTagType","refetchQuery","internalState","removeQueryResult","isThunkActionWithTags","isQueryEnd","pendingTagInvalidations","pendingRequestCount","handler","action","mwApi","invalidateTags","calculateProvidedByThunk","calculateProvidedBy","hasPendingRequests","newTags","rootState","state","tags","toInvalidate","valuesArray","queryCacheKey","querySubState","subscriptionSubState","getOrInsertComputed","createNewMap","STATUS_UNINITIALIZED","buildPollingHandler","reducerPath","queryThunk","api","refetchQuery","internalState","currentPolls","currentSubscriptions","pendingPollingUpdates","pollingUpdateTimer","handler","action","mwApi","schedulePollingUpdate","startNextPoll","clearPolls","queryCacheKey","key","updatePollingInterval","state","querySubState","subscriptions","STATUS_UNINITIALIZED","lowestPollingInterval","skipPollingIfUnfocused","findLowestPollingInterval","currentPoll","nextPollTimestamp","cleanupPollForKey","existingPoll","subscribers","entry","buildQueryLifecycleHandler","api","context","queryThunk","mutationThunk","isPendingThunk","isRejectedThunk","isFullfilledThunk","lifecycleMap","action","mwApi","requestId","endpointName","originalArgs","endpointDefinition","getEndpointDefinition","onQueryStarted","lifecycle","queryFulfilled","resolve","reject","selector","isAnyQueryDefinition","extra","_","__","lifecycleApi","updateRecipe","baseQueryMeta","rejectedWithValue","buildWindowEventHandler","reducerPath","context","api","refetchQuery","internalState","removeQueryResult","handler","action","mwApi","onFocus","refetchValidQueries","onOnline","type","state","queries","subscriptions","queryCacheKey","querySubState","subscriptionSubState","values","sub","STATUS_UNINITIALIZED","buildMiddleware","input","reducerPath","queryThunk","api","context","getInternalState","apiUid","actions","isThisApiSliceAction","action","handlerBuilders","buildDevCheckHandler","buildCacheCollectionHandler","buildInvalidationByTagsHandler","buildPollingHandler","buildCacheLifecycleHandler","buildQueryLifecycleHandler","mwApi","initialized","internalState","builderArgs","refetchQuery","handlers","build","batchedActionsHandler","buildBatchedActionsHandler","windowEventsHandler","buildWindowEventHandler","next","mwApiWithNext","stateBefore","actionShouldContinue","internalProbeResult","res","handler","querySubState","coreModuleName","coreModule","createSelector","api","baseQuery","tagTypes","reducerPath","serializeQueryArgs","keepUnusedDataFor","refetchOnMountOrArgChange","refetchOnFocus","refetchOnReconnect","invalidationBehavior","onSchemaFailure","catchSchemaFailure","skipSchemaValidation","context","assertTagType","tag","onOnline","onOffline","onFocus","onFocusLost","selectors","buildSelectors","selectInvalidatedBy","selectCachedArgsForQuery","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","safeAssign","queryThunk","infiniteQueryThunk","mutationThunk","patchQueryData","updateQueryData","upsertQueryData","prefetch","buildMatchThunkActions","buildThunks","reducer","sliceActions","buildSlice","internalStateMap","getInternalState","dispatch","getOrInsertComputed","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningMutationThunk","getRunningMutationsThunk","getRunningQueriesThunk","getRunningQueryThunk","buildInitiate","middleware","middlewareActions","buildMiddleware","endpointName","definition","anyApi","endpoint","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","createApi","buildCreateApi","coreModule"]}
Index: node_modules/@reduxjs/toolkit/dist/query/index.d.mts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2954 @@
+import * as _reduxjs_toolkit from '@reduxjs/toolkit';
+import { ThunkDispatch, UnknownAction, Draft, AsyncThunk, SHOULD_AUTOBATCH, ThunkAction, SafePromise, SerializedError, PayloadAction, ActionCreatorWithoutPayload, Reducer, Middleware, ActionCreatorWithPayload } from '@reduxjs/toolkit';
+import { Patch } from 'immer';
+import * as redux from 'redux';
+import { CreateSelectorFunction } from 'reselect';
+import { StandardSchemaV1 } from '@standard-schema/spec';
+import { SchemaError } from '@standard-schema/utils';
+
+type Id<T> = {
+    [K in keyof T]: T[K];
+} & {};
+type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
+type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
+type NonOptionalKeys<T> = {
+    [K in keyof T]-?: undefined extends T[K] ? never : K;
+}[keyof T];
+type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;
+type NoInfer<T> = [T][T extends any ? 0 : never];
+type NonUndefined<T> = T extends undefined ? never : T;
+type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;
+type MaybePromise<T> = T | PromiseLike<T>;
+type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;
+type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
+type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
+
+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;
+}
+type QueryReturnValue<T = unknown, E = unknown, M = unknown> = {
+    error: E;
+    data?: undefined;
+    meta?: M;
+} | {
+    error?: undefined;
+    data: T;
+    meta?: M;
+};
+type BaseQueryFn<Args = any, Result = unknown, Error = unknown, DefinitionExtraOptions = {}, Meta = {}> = (args: Args, api: BaseQueryApi, extraOptions: DefinitionExtraOptions) => MaybePromise<QueryReturnValue<Result, Error, Meta>>;
+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
+ */
+type BaseQueryResult<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped ? Unwrapped extends {
+    data: any;
+} ? Unwrapped['data'] : never : never;
+/**
+ * @public
+ */
+type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>>['meta'];
+/**
+ * @public
+ */
+type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<UnwrapPromise<ReturnType<BaseQuery>>, {
+    error?: undefined;
+}>['error'];
+/**
+ * @public
+ */
+type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> = T extends (arg: infer A, ...args: any[]) => any ? A : any;
+/**
+ * @public
+ */
+type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> = Parameters<BaseQuery>[2];
+
+declare const defaultSerializeQueryArgs: SerializeQueryArgs<any>;
+type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
+    queryArgs: QueryArgs;
+    endpointDefinition: EndpointDefinition<any, any, any, any>;
+    endpointName: string;
+}) => ReturnType;
+type InternalSerializeQueryArgs = (_: {
+    queryArgs: any;
+    endpointDefinition: EndpointDefinition<any, any, any, any>;
+    endpointName: string;
+}) => QueryCacheKey;
+
+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[];
+}
+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`.
+ */
+declare function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']>;
+
+type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;
+type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;
+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;
+type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;
+type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;
+type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;
+type Matcher<M> = (value: any) => value is M;
+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>>;
+}
+type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {
+    type: 'query';
+    originalArgs: unknown;
+    endpointName: string;
+};
+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;
+};
+type ThunkResult = unknown;
+type ThunkApiMetaConfig = {
+    pendingMeta: {
+        startedTimeStamp: number;
+        [SHOULD_AUTOBATCH]: true;
+    };
+    fulfilledMeta: {
+        fulfilledTimeStamp: number;
+        baseQueryMeta: unknown;
+        [SHOULD_AUTOBATCH]: true;
+    };
+    rejectedMeta: {
+        baseQueryMeta: unknown;
+        [SHOULD_AUTOBATCH]: true;
+    };
+};
+type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;
+type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;
+type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;
+type MaybeDrafted<T> = T | Draft<T>;
+type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;
+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>;
+type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;
+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;
+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;
+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>;
+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>;
+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.
+ */
+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 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 declare const skipToken: unique symbol;
+type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
+    select: QueryResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
+};
+type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
+    select: InfiniteQueryResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
+};
+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>;
+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>;
+type InfiniteQueryResultFlags = {
+    hasNextPage: boolean;
+    hasPreviousPage: boolean;
+    isFetchingNextPage: boolean;
+    isFetchingPreviousPage: boolean;
+    isFetchNextPageError: boolean;
+    isFetchPreviousPageError: boolean;
+};
+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>;
+type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;
+
+type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {
+    initiate: StartQueryActionCreator<Definition>;
+};
+type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
+    initiate: StartInfiniteQueryActionCreator<Definition>;
+};
+type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {
+    initiate: StartMutationActionCreator<Definition>;
+};
+declare const forceQueryFnSymbol: unique symbol;
+type StartQueryActionCreatorOptions = {
+    subscribe?: boolean;
+    forceRefetch?: boolean | number;
+    subscriptionOptions?: SubscriptionOptions;
+    [forceQueryFnSymbol]?: () => QueryReturnValue;
+};
+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 StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;
+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 QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {
+    arg: QueryArgFrom<D>;
+    unwrap(): Promise<ResultTypeFrom<D>>;
+    refetch(): QueryActionCreatorResult<D>;
+};
+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>;
+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;
+};
+
+type ReferenceCacheLifecycle = never;
+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;
+}
+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>;
+};
+interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
+}
+type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;
+type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
+    onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
+};
+type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;
+type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
+    onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
+};
+declare const neverResolvedError: Error & {
+    message: "Promise never resolved before cacheEntryRemoved.";
+};
+
+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;
+};
+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;
+};
+type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;
+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;
+};
+interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
+}
+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
+ */
+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
+ */
+type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];
+
+/**
+ * A typesafe single entry to be upserted into the cache
+ */
+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;
+};
+type ProcessedQueryUpsertEntry = {
+    queryDescription: QueryThunkArg;
+    value: unknown;
+};
+/**
+ * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert
+ */
+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[]>;
+};
+declare 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'>;
+}): {
+    reducer: redux.Reducer<{
+        queries: QueryState<any>;
+        mutations: MutationState<any>;
+        provided: InvalidationState<string>;
+        subscriptions: SubscriptionState;
+        config: ConfigState<string>;
+    }, redux.UnknownAction, Partial<{
+        queries: QueryState<any> | undefined;
+        mutations: MutationState<any> | undefined;
+        provided: InvalidationState<string> | undefined;
+        subscriptions: SubscriptionState | undefined;
+        config: ConfigState<string> | undefined;
+    }>>;
+    actions: {
+        resetApiState: _reduxjs_toolkit.ActionCreatorWithoutPayload<`${string}/resetApiState`>;
+        updateProvidedBy: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
+            queryCacheKey: QueryCacheKey;
+            providedTags: readonly FullTagDescription<string>[];
+        }[]], {
+            queryCacheKey: QueryCacheKey;
+            providedTags: readonly FullTagDescription<string>[];
+        }[], `${string}/invalidation/updateProvidedBy`, never, unknown>;
+        removeMutationResult: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/mutations/removeMutationResult`, never, unknown>;
+        subscriptionsUpdated: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: Patch[]], Patch[], `${string}/internalSubscriptions/subscriptionsUpdated`, never, unknown>;
+        updateSubscriptionOptions: _reduxjs_toolkit.ActionCreatorWithPayload<{
+            endpointName: string;
+            requestId: string;
+            options: Subscribers[number];
+        } & QuerySubstateIdentifier, `${string}/subscriptions/updateSubscriptionOptions`>;
+        unsubscribeQueryResult: _reduxjs_toolkit.ActionCreatorWithPayload<{
+            requestId: string;
+        } & QuerySubstateIdentifier, `${string}/subscriptions/unsubscribeQueryResult`>;
+        internal_getRTKQSubscriptions: _reduxjs_toolkit.ActionCreatorWithoutPayload<`${string}/subscriptions/internal_getRTKQSubscriptions`>;
+        removeQueryResult: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier], QuerySubstateIdentifier, `${string}/queries/removeQueryResult`, never, unknown>;
+        cacheEntriesUpserted: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: NormalizedQueryUpsertEntryPayload[]], ProcessedQueryUpsertEntry[], `${string}/queries/cacheEntriesUpserted`, never, {
+            RTK_autoBatch: boolean;
+            requestId: string;
+            timestamp: number;
+        }>;
+        queryResultPatched: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier & {
+            patches: readonly Patch[];
+        }], QuerySubstateIdentifier & {
+            patches: readonly Patch[];
+        }, `${string}/queries/queryResultPatched`, never, unknown>;
+        middlewareRegistered: _reduxjs_toolkit.ActionCreatorWithPayload<string, `${string}/config/middlewareRegistered`>;
+    };
+};
+type SliceActions = ReturnType<typeof buildSlice>['actions'];
+
+declare const onFocus: ActionCreatorWithoutPayload<"__rtkq/focused">;
+declare const onFocusLost: ActionCreatorWithoutPayload<"__rtkq/unfocused">;
+declare const onOnline: ActionCreatorWithoutPayload<"__rtkq/online">;
+declare const onOffline: ActionCreatorWithoutPayload<"__rtkq/offline">;
+/**
+ * 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.
+ */
+declare 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): () => void;
+
+/**
+ * Note: this file should import all other files for type discovery and declaration merging
+ */
+
+/**
+ * `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.
+ */
+type PrefetchOptions = {
+    ifOlderThan?: false | number;
+} | {
+    force?: boolean;
+};
+export declare const coreModuleName: unique symbol;
+type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
+type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;
+interface ApiModules<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;
+        };
+    };
+}
+interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, 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']>;
+}
+interface ApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, 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']>;
+}
+interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, 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']>;
+}
+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;
+};
+type InternalActions = SliceActions & ListenerActions;
+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());
+ * ```
+ */
+declare const coreModule: ({ createSelector, }?: CoreModuleOptions) => Module<CoreModule>;
+
+declare const createApi: CreateApi<typeof coreModuleName>;
+
+type ModuleName = keyof ApiModules<any, any, any, any>;
+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;
+    };
+};
+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;
+}
+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>;
+};
+
+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>;
+};
+
+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
+ *     })
+ *   })
+ * })
+ * ```
+ */
+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;
+};
+
+export declare const _NEVER: unique symbol;
+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.
+ */
+declare function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}>;
+
+declare class NamedSchemaError extends SchemaError {
+    readonly value: any;
+    readonly schemaName: `${SchemaType}Schema`;
+    readonly _bqMeta: any;
+    constructor(issues: readonly StandardSchemaV1.Issue[], value: any, schemaName: `${SchemaType}Schema`, _bqMeta: any);
+}
+
+declare const rawResultType: unique symbol;
+declare const resultType: unique symbol;
+declare const baseQuery: unique symbol;
+interface SchemaFailureInfo {
+    endpoint: string;
+    arg: any;
+    type: 'query' | 'mutation';
+    queryCacheKey?: string;
+}
+type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;
+type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;
+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>>;
+};
+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;
+};
+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[];
+}
+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> & {
+    [rawResultType]?: RawResultType;
+    [resultType]?: ResultType;
+    [baseQuery]?: BaseQuery;
+} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {
+    extraOptions: BaseQueryExtraOptions<BaseQuery>;
+}, {
+    extraOptions?: BaseQueryExtraOptions<BaseQuery>;
+}>;
+declare enum DefinitionType {
+    query = "query",
+    mutation = "mutation",
+    infinitequery = "infinitequery"
+}
+type TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;
+type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;
+type FullTagDescription<TagType> = {
+    type: TagType;
+    id?: number | string;
+};
+type TagDescription<TagType> = TagType | FullTagDescription<TagType>;
+/**
+ * @public
+ */
+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
+ */
+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>;
+}
+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>;
+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;
+};
+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>;
+}
+type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = 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
+ */
+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>;
+}
+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>;
+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>;
+type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;
+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>;
+};
+type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;
+type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;
+type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;
+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;
+type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;
+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;
+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;
+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;
+type InfiniteQueryCombinedArg<QueryArg, PageParam> = {
+    queryArg: QueryArg;
+    pageParam: PageParam;
+};
+type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;
+type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;
+type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;
+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;
+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;
+};
+
+type QueryCacheKey = string & {
+    _type: 'queryCacheKey';
+};
+type QuerySubstateIdentifier = {
+    queryCacheKey: QueryCacheKey;
+};
+type MutationSubstateIdentifier = {
+    requestId: string;
+    fixedCacheKey?: string;
+} | {
+    requestId?: string;
+    fixedCacheKey: string;
+};
+type RefetchConfigOptions = {
+    refetchOnMountOrArgChange: boolean | number;
+    refetchOnReconnect: boolean;
+    refetchOnFocus: boolean;
+};
+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;
+};
+type InfiniteData<DataType, PageParam> = {
+    pages: Array<DataType>;
+    pageParams: Array<PageParam>;
+};
+/**
+ * Strings describing the query state at any given time.
+ */
+declare enum QueryStatus {
+    uninitialized = "uninitialized",
+    pending = "pending",
+    fulfilled = "fulfilled",
+    rejected = "rejected"
+}
+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;
+};
+/**
+ * @public
+ */
+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;
+};
+type Subscribers = {
+    [requestId: string]: SubscriptionOptions;
+};
+type QueryKeys<Definitions extends EndpointDefinitions> = {
+    [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never;
+}[keyof Definitions];
+type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {
+    [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never;
+}[keyof Definitions];
+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;
+};
+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;
+}>;
+type InfiniteQueryDirection = 'forward' | 'backward';
+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;
+};
+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;
+};
+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>;
+};
+type InvalidationState<TagTypes extends string> = {
+    tags: {
+        [_ in TagTypes]: {
+            [id: string]: Array<QueryCacheKey>;
+            [id: number]: Array<QueryCacheKey>;
+        };
+    };
+    keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;
+};
+type QueryState<D extends EndpointDefinitions> = {
+    [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;
+};
+type SubscriptionState = {
+    [queryCacheKey: string]: Subscribers | undefined;
+};
+type ConfigState<ReducerPath> = RefetchConfigOptions & {
+    reducerPath: ReducerPath;
+    online: boolean;
+    focused: boolean;
+    middlewareRegistered: boolean | 'conflict';
+} & ModifiableConfigState;
+type ModifiableConfigState = {
+    keepUnusedDataFor: number;
+    invalidationBehavior: 'delayed' | 'immediately';
+} & RefetchConfigOptions;
+type MutationState<D extends EndpointDefinitions> = {
+    [requestId: string]: MutationSubState<D[string]> | undefined;
+};
+type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = {
+    [P in ReducerPath]: CombinedState<Definitions, TagTypes, P>;
+};
+
+type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);
+type CustomRequestInit = Override<RequestInit, {
+    headers?: Headers | string[][] | Record<string, string | undefined> | undefined;
+}>;
+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;
+}
+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;
+};
+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'>;
+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.
+ */
+declare function fetchBaseQuery({ baseUrl, prepareHeaders, fetchFn, paramsSerializer, isJsonContentType, jsonContentType, jsonReplacer, timeout: defaultTimeout, responseHandler: globalResponseHandler, validateStatus: globalValidateStatus, ...baseFetchOptions }?: FetchBaseQueryArgs): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
+
+type RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {
+    attempt: number;
+    baseQueryApi: BaseQueryApi;
+    extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;
+}) => boolean;
+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;
+});
+declare function fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never;
+/**
+ * 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;
+ * ```
+ */
+declare const retry: BaseQueryEnhancer<unknown, RetryOptions, void | RetryOptions> & {
+    fail: typeof fail;
+};
+
+declare function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;
+
+export { type Api, type ApiContext, type ApiEndpointInfiniteQuery, type ApiEndpointMutation, type ApiEndpointQuery, type ApiModules, type BaseEndpointDefinition, type BaseQueryApi, type BaseQueryArg, type BaseQueryEnhancer, type BaseQueryError, type BaseQueryExtraOptions, type BaseQueryFn, type BaseQueryMeta, type BaseQueryResult, type CombinedState, type CoreModule, type CreateApi, type CreateApiOptions, DefinitionType, type DefinitionsFromApi, type EndpointBuilder, type EndpointDefinition, type EndpointDefinitions, type FetchArgs, type FetchBaseQueryArgs, type FetchBaseQueryError, type FetchBaseQueryMeta, type InfiniteData, type InfiniteQueryActionCreatorResult, type InfiniteQueryArgFrom, type InfiniteQueryConfigOptions, type InfiniteQueryDefinition, type InfiniteQueryExtraOptions, type InfiniteQueryResultSelectorResult, type InfiniteQuerySubState, type Module, type MutationActionCreatorResult, type MutationDefinition, type MutationExtraOptions, type MutationResultSelectorResult, NamedSchemaError, type OverrideResultType, type PageParamFrom, type PrefetchOptions, type QueryActionCreatorResult, type QueryArgFrom, type QueryCacheKey, type QueryDefinition, type QueryExtraOptions, type QueryKeys, type QueryResultSelectorResult, type QueryReturnValue, QueryStatus, type QuerySubState, type ResultDescription, type ResultTypeFrom, type RetryOptions, type RootState, type SchemaFailureConverter, type SchemaFailureHandler, type SchemaFailureInfo, type SchemaType, type SerializeQueryArgs, type SkipToken, type StartQueryActionCreatorOptions, type SubscriptionOptions, type Id as TSHelpersId, type NoInfer as TSHelpersNoInfer, type Override as TSHelpersOverride, type TagDescription, type TagTypesFromApi, type TypedMutationOnQueryStarted, type TypedQueryOnQueryStarted, type UpdateDefinitions, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, defaultSerializeQueryArgs, fakeBaseQuery, fetchBaseQuery, retry, setupListeners };
Index: node_modules/@reduxjs/toolkit/dist/query/index.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2954 @@
+import * as _reduxjs_toolkit from '@reduxjs/toolkit';
+import { ThunkDispatch, UnknownAction, Draft, AsyncThunk, SHOULD_AUTOBATCH, ThunkAction, SafePromise, SerializedError, PayloadAction, ActionCreatorWithoutPayload, Reducer, Middleware, ActionCreatorWithPayload } from '@reduxjs/toolkit';
+import { Patch } from 'immer';
+import * as redux from 'redux';
+import { CreateSelectorFunction } from 'reselect';
+import { StandardSchemaV1 } from '@standard-schema/spec';
+import { SchemaError } from '@standard-schema/utils';
+
+type Id<T> = {
+    [K in keyof T]: T[K];
+} & {};
+type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
+type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
+type NonOptionalKeys<T> = {
+    [K in keyof T]-?: undefined extends T[K] ? never : K;
+}[keyof T];
+type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;
+type NoInfer<T> = [T][T extends any ? 0 : never];
+type NonUndefined<T> = T extends undefined ? never : T;
+type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;
+type MaybePromise<T> = T | PromiseLike<T>;
+type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;
+type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
+type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
+
+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;
+}
+type QueryReturnValue<T = unknown, E = unknown, M = unknown> = {
+    error: E;
+    data?: undefined;
+    meta?: M;
+} | {
+    error?: undefined;
+    data: T;
+    meta?: M;
+};
+type BaseQueryFn<Args = any, Result = unknown, Error = unknown, DefinitionExtraOptions = {}, Meta = {}> = (args: Args, api: BaseQueryApi, extraOptions: DefinitionExtraOptions) => MaybePromise<QueryReturnValue<Result, Error, Meta>>;
+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
+ */
+type BaseQueryResult<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped ? Unwrapped extends {
+    data: any;
+} ? Unwrapped['data'] : never : never;
+/**
+ * @public
+ */
+type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>>['meta'];
+/**
+ * @public
+ */
+type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<UnwrapPromise<ReturnType<BaseQuery>>, {
+    error?: undefined;
+}>['error'];
+/**
+ * @public
+ */
+type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> = T extends (arg: infer A, ...args: any[]) => any ? A : any;
+/**
+ * @public
+ */
+type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> = Parameters<BaseQuery>[2];
+
+declare const defaultSerializeQueryArgs: SerializeQueryArgs<any>;
+type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
+    queryArgs: QueryArgs;
+    endpointDefinition: EndpointDefinition<any, any, any, any>;
+    endpointName: string;
+}) => ReturnType;
+type InternalSerializeQueryArgs = (_: {
+    queryArgs: any;
+    endpointDefinition: EndpointDefinition<any, any, any, any>;
+    endpointName: string;
+}) => QueryCacheKey;
+
+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[];
+}
+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`.
+ */
+declare function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']>;
+
+type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;
+type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;
+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;
+type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;
+type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;
+type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;
+type Matcher<M> = (value: any) => value is M;
+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>>;
+}
+type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {
+    type: 'query';
+    originalArgs: unknown;
+    endpointName: string;
+};
+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;
+};
+type ThunkResult = unknown;
+type ThunkApiMetaConfig = {
+    pendingMeta: {
+        startedTimeStamp: number;
+        [SHOULD_AUTOBATCH]: true;
+    };
+    fulfilledMeta: {
+        fulfilledTimeStamp: number;
+        baseQueryMeta: unknown;
+        [SHOULD_AUTOBATCH]: true;
+    };
+    rejectedMeta: {
+        baseQueryMeta: unknown;
+        [SHOULD_AUTOBATCH]: true;
+    };
+};
+type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;
+type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;
+type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;
+type MaybeDrafted<T> = T | Draft<T>;
+type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;
+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>;
+type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;
+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;
+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;
+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>;
+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>;
+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.
+ */
+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 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 declare const skipToken: unique symbol;
+type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
+    select: QueryResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
+};
+type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
+    select: InfiniteQueryResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
+};
+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>;
+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>;
+type InfiniteQueryResultFlags = {
+    hasNextPage: boolean;
+    hasPreviousPage: boolean;
+    isFetchingNextPage: boolean;
+    isFetchingPreviousPage: boolean;
+    isFetchNextPageError: boolean;
+    isFetchPreviousPageError: boolean;
+};
+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>;
+type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;
+
+type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {
+    initiate: StartQueryActionCreator<Definition>;
+};
+type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
+    initiate: StartInfiniteQueryActionCreator<Definition>;
+};
+type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {
+    initiate: StartMutationActionCreator<Definition>;
+};
+declare const forceQueryFnSymbol: unique symbol;
+type StartQueryActionCreatorOptions = {
+    subscribe?: boolean;
+    forceRefetch?: boolean | number;
+    subscriptionOptions?: SubscriptionOptions;
+    [forceQueryFnSymbol]?: () => QueryReturnValue;
+};
+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 StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;
+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 QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {
+    arg: QueryArgFrom<D>;
+    unwrap(): Promise<ResultTypeFrom<D>>;
+    refetch(): QueryActionCreatorResult<D>;
+};
+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>;
+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;
+};
+
+type ReferenceCacheLifecycle = never;
+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;
+}
+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>;
+};
+interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
+}
+type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;
+type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
+    onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
+};
+type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;
+type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
+    onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
+};
+declare const neverResolvedError: Error & {
+    message: "Promise never resolved before cacheEntryRemoved.";
+};
+
+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;
+};
+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;
+};
+type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;
+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;
+};
+interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
+}
+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
+ */
+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
+ */
+type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];
+
+/**
+ * A typesafe single entry to be upserted into the cache
+ */
+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;
+};
+type ProcessedQueryUpsertEntry = {
+    queryDescription: QueryThunkArg;
+    value: unknown;
+};
+/**
+ * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert
+ */
+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[]>;
+};
+declare 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'>;
+}): {
+    reducer: redux.Reducer<{
+        queries: QueryState<any>;
+        mutations: MutationState<any>;
+        provided: InvalidationState<string>;
+        subscriptions: SubscriptionState;
+        config: ConfigState<string>;
+    }, redux.UnknownAction, Partial<{
+        queries: QueryState<any> | undefined;
+        mutations: MutationState<any> | undefined;
+        provided: InvalidationState<string> | undefined;
+        subscriptions: SubscriptionState | undefined;
+        config: ConfigState<string> | undefined;
+    }>>;
+    actions: {
+        resetApiState: _reduxjs_toolkit.ActionCreatorWithoutPayload<`${string}/resetApiState`>;
+        updateProvidedBy: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
+            queryCacheKey: QueryCacheKey;
+            providedTags: readonly FullTagDescription<string>[];
+        }[]], {
+            queryCacheKey: QueryCacheKey;
+            providedTags: readonly FullTagDescription<string>[];
+        }[], `${string}/invalidation/updateProvidedBy`, never, unknown>;
+        removeMutationResult: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/mutations/removeMutationResult`, never, unknown>;
+        subscriptionsUpdated: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: Patch[]], Patch[], `${string}/internalSubscriptions/subscriptionsUpdated`, never, unknown>;
+        updateSubscriptionOptions: _reduxjs_toolkit.ActionCreatorWithPayload<{
+            endpointName: string;
+            requestId: string;
+            options: Subscribers[number];
+        } & QuerySubstateIdentifier, `${string}/subscriptions/updateSubscriptionOptions`>;
+        unsubscribeQueryResult: _reduxjs_toolkit.ActionCreatorWithPayload<{
+            requestId: string;
+        } & QuerySubstateIdentifier, `${string}/subscriptions/unsubscribeQueryResult`>;
+        internal_getRTKQSubscriptions: _reduxjs_toolkit.ActionCreatorWithoutPayload<`${string}/subscriptions/internal_getRTKQSubscriptions`>;
+        removeQueryResult: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier], QuerySubstateIdentifier, `${string}/queries/removeQueryResult`, never, unknown>;
+        cacheEntriesUpserted: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: NormalizedQueryUpsertEntryPayload[]], ProcessedQueryUpsertEntry[], `${string}/queries/cacheEntriesUpserted`, never, {
+            RTK_autoBatch: boolean;
+            requestId: string;
+            timestamp: number;
+        }>;
+        queryResultPatched: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier & {
+            patches: readonly Patch[];
+        }], QuerySubstateIdentifier & {
+            patches: readonly Patch[];
+        }, `${string}/queries/queryResultPatched`, never, unknown>;
+        middlewareRegistered: _reduxjs_toolkit.ActionCreatorWithPayload<string, `${string}/config/middlewareRegistered`>;
+    };
+};
+type SliceActions = ReturnType<typeof buildSlice>['actions'];
+
+declare const onFocus: ActionCreatorWithoutPayload<"__rtkq/focused">;
+declare const onFocusLost: ActionCreatorWithoutPayload<"__rtkq/unfocused">;
+declare const onOnline: ActionCreatorWithoutPayload<"__rtkq/online">;
+declare const onOffline: ActionCreatorWithoutPayload<"__rtkq/offline">;
+/**
+ * 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.
+ */
+declare 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): () => void;
+
+/**
+ * Note: this file should import all other files for type discovery and declaration merging
+ */
+
+/**
+ * `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.
+ */
+type PrefetchOptions = {
+    ifOlderThan?: false | number;
+} | {
+    force?: boolean;
+};
+export declare const coreModuleName: unique symbol;
+type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
+type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;
+interface ApiModules<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;
+        };
+    };
+}
+interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, 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']>;
+}
+interface ApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, 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']>;
+}
+interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, 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']>;
+}
+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;
+};
+type InternalActions = SliceActions & ListenerActions;
+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());
+ * ```
+ */
+declare const coreModule: ({ createSelector, }?: CoreModuleOptions) => Module<CoreModule>;
+
+declare const createApi: CreateApi<typeof coreModuleName>;
+
+type ModuleName = keyof ApiModules<any, any, any, any>;
+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;
+    };
+};
+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;
+}
+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>;
+};
+
+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>;
+};
+
+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
+ *     })
+ *   })
+ * })
+ * ```
+ */
+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;
+};
+
+export declare const _NEVER: unique symbol;
+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.
+ */
+declare function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}>;
+
+declare class NamedSchemaError extends SchemaError {
+    readonly value: any;
+    readonly schemaName: `${SchemaType}Schema`;
+    readonly _bqMeta: any;
+    constructor(issues: readonly StandardSchemaV1.Issue[], value: any, schemaName: `${SchemaType}Schema`, _bqMeta: any);
+}
+
+declare const rawResultType: unique symbol;
+declare const resultType: unique symbol;
+declare const baseQuery: unique symbol;
+interface SchemaFailureInfo {
+    endpoint: string;
+    arg: any;
+    type: 'query' | 'mutation';
+    queryCacheKey?: string;
+}
+type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;
+type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;
+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>>;
+};
+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;
+};
+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[];
+}
+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> & {
+    [rawResultType]?: RawResultType;
+    [resultType]?: ResultType;
+    [baseQuery]?: BaseQuery;
+} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {
+    extraOptions: BaseQueryExtraOptions<BaseQuery>;
+}, {
+    extraOptions?: BaseQueryExtraOptions<BaseQuery>;
+}>;
+declare enum DefinitionType {
+    query = "query",
+    mutation = "mutation",
+    infinitequery = "infinitequery"
+}
+type TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;
+type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;
+type FullTagDescription<TagType> = {
+    type: TagType;
+    id?: number | string;
+};
+type TagDescription<TagType> = TagType | FullTagDescription<TagType>;
+/**
+ * @public
+ */
+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
+ */
+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>;
+}
+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>;
+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;
+};
+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>;
+}
+type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = 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
+ */
+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>;
+}
+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>;
+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>;
+type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;
+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>;
+};
+type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;
+type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;
+type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;
+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;
+type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;
+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;
+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;
+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;
+type InfiniteQueryCombinedArg<QueryArg, PageParam> = {
+    queryArg: QueryArg;
+    pageParam: PageParam;
+};
+type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;
+type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;
+type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;
+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;
+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;
+};
+
+type QueryCacheKey = string & {
+    _type: 'queryCacheKey';
+};
+type QuerySubstateIdentifier = {
+    queryCacheKey: QueryCacheKey;
+};
+type MutationSubstateIdentifier = {
+    requestId: string;
+    fixedCacheKey?: string;
+} | {
+    requestId?: string;
+    fixedCacheKey: string;
+};
+type RefetchConfigOptions = {
+    refetchOnMountOrArgChange: boolean | number;
+    refetchOnReconnect: boolean;
+    refetchOnFocus: boolean;
+};
+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;
+};
+type InfiniteData<DataType, PageParam> = {
+    pages: Array<DataType>;
+    pageParams: Array<PageParam>;
+};
+/**
+ * Strings describing the query state at any given time.
+ */
+declare enum QueryStatus {
+    uninitialized = "uninitialized",
+    pending = "pending",
+    fulfilled = "fulfilled",
+    rejected = "rejected"
+}
+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;
+};
+/**
+ * @public
+ */
+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;
+};
+type Subscribers = {
+    [requestId: string]: SubscriptionOptions;
+};
+type QueryKeys<Definitions extends EndpointDefinitions> = {
+    [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never;
+}[keyof Definitions];
+type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {
+    [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never;
+}[keyof Definitions];
+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;
+};
+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;
+}>;
+type InfiniteQueryDirection = 'forward' | 'backward';
+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;
+};
+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;
+};
+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>;
+};
+type InvalidationState<TagTypes extends string> = {
+    tags: {
+        [_ in TagTypes]: {
+            [id: string]: Array<QueryCacheKey>;
+            [id: number]: Array<QueryCacheKey>;
+        };
+    };
+    keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;
+};
+type QueryState<D extends EndpointDefinitions> = {
+    [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;
+};
+type SubscriptionState = {
+    [queryCacheKey: string]: Subscribers | undefined;
+};
+type ConfigState<ReducerPath> = RefetchConfigOptions & {
+    reducerPath: ReducerPath;
+    online: boolean;
+    focused: boolean;
+    middlewareRegistered: boolean | 'conflict';
+} & ModifiableConfigState;
+type ModifiableConfigState = {
+    keepUnusedDataFor: number;
+    invalidationBehavior: 'delayed' | 'immediately';
+} & RefetchConfigOptions;
+type MutationState<D extends EndpointDefinitions> = {
+    [requestId: string]: MutationSubState<D[string]> | undefined;
+};
+type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = {
+    [P in ReducerPath]: CombinedState<Definitions, TagTypes, P>;
+};
+
+type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);
+type CustomRequestInit = Override<RequestInit, {
+    headers?: Headers | string[][] | Record<string, string | undefined> | undefined;
+}>;
+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;
+}
+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;
+};
+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'>;
+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.
+ */
+declare function fetchBaseQuery({ baseUrl, prepareHeaders, fetchFn, paramsSerializer, isJsonContentType, jsonContentType, jsonReplacer, timeout: defaultTimeout, responseHandler: globalResponseHandler, validateStatus: globalValidateStatus, ...baseFetchOptions }?: FetchBaseQueryArgs): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
+
+type RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {
+    attempt: number;
+    baseQueryApi: BaseQueryApi;
+    extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;
+}) => boolean;
+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;
+});
+declare function fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never;
+/**
+ * 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;
+ * ```
+ */
+declare const retry: BaseQueryEnhancer<unknown, RetryOptions, void | RetryOptions> & {
+    fail: typeof fail;
+};
+
+declare function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;
+
+export { type Api, type ApiContext, type ApiEndpointInfiniteQuery, type ApiEndpointMutation, type ApiEndpointQuery, type ApiModules, type BaseEndpointDefinition, type BaseQueryApi, type BaseQueryArg, type BaseQueryEnhancer, type BaseQueryError, type BaseQueryExtraOptions, type BaseQueryFn, type BaseQueryMeta, type BaseQueryResult, type CombinedState, type CoreModule, type CreateApi, type CreateApiOptions, DefinitionType, type DefinitionsFromApi, type EndpointBuilder, type EndpointDefinition, type EndpointDefinitions, type FetchArgs, type FetchBaseQueryArgs, type FetchBaseQueryError, type FetchBaseQueryMeta, type InfiniteData, type InfiniteQueryActionCreatorResult, type InfiniteQueryArgFrom, type InfiniteQueryConfigOptions, type InfiniteQueryDefinition, type InfiniteQueryExtraOptions, type InfiniteQueryResultSelectorResult, type InfiniteQuerySubState, type Module, type MutationActionCreatorResult, type MutationDefinition, type MutationExtraOptions, type MutationResultSelectorResult, NamedSchemaError, type OverrideResultType, type PageParamFrom, type PrefetchOptions, type QueryActionCreatorResult, type QueryArgFrom, type QueryCacheKey, type QueryDefinition, type QueryExtraOptions, type QueryKeys, type QueryResultSelectorResult, type QueryReturnValue, QueryStatus, type QuerySubState, type ResultDescription, type ResultTypeFrom, type RetryOptions, type RootState, type SchemaFailureConverter, type SchemaFailureHandler, type SchemaFailureInfo, type SchemaType, type SerializeQueryArgs, type SkipToken, type StartQueryActionCreatorOptions, type SubscriptionOptions, type Id as TSHelpersId, type NoInfer as TSHelpersNoInfer, type Override as TSHelpersOverride, type TagDescription, type TagTypesFromApi, type TypedMutationOnQueryStarted, type TypedQueryOnQueryStarted, type UpdateDefinitions, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, defaultSerializeQueryArgs, fakeBaseQuery, fetchBaseQuery, retry, setupListeners };
Index: node_modules/@reduxjs/toolkit/dist/query/react/cjs/index.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+'use strict'
+if (process.env.NODE_ENV === 'production') {
+  module.exports = require('./rtk-query-react.production.min.cjs')
+} else {
+  module.exports = require('./rtk-query-react.development.cjs')
+}
Index: node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.development.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,748 @@
+"use strict";
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+  // If the importer is in node compatibility mode or this is not an ESM
+  // file that has been converted to a CommonJS file using a Babel-
+  // compatible transform (i.e. "__esModule" has not been set), then set
+  // "default" to the CommonJS "module.exports" for node compatibility.
+  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+  mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// src/query/react/index.ts
+var react_exports = {};
+__export(react_exports, {
+  ApiProvider: () => ApiProvider,
+  UNINITIALIZED_VALUE: () => UNINITIALIZED_VALUE,
+  createApi: () => createApi,
+  reactHooksModule: () => reactHooksModule,
+  reactHooksModuleName: () => reactHooksModuleName
+});
+module.exports = __toCommonJS(react_exports);
+
+// src/query/react/rtkqImports.ts
+var import_query = require("@reduxjs/toolkit/query");
+
+// src/query/react/module.ts
+var import_toolkit2 = require("@reduxjs/toolkit");
+var import_react_redux2 = require("react-redux");
+var import_reselect = require("reselect");
+
+// src/query/utils/capitalize.ts
+function capitalize(str) {
+  return str.replace(str[0], str[0].toUpperCase());
+}
+
+// src/query/utils/countObjectKeys.ts
+function countObjectKeys(obj) {
+  let count = 0;
+  for (const _key in obj) {
+    count++;
+  }
+  return count;
+}
+
+// src/query/endpointDefinitions.ts
+var ENDPOINT_QUERY = "query" /* query */;
+var ENDPOINT_MUTATION = "mutation" /* mutation */;
+var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
+function isQueryDefinition(e) {
+  return e.type === ENDPOINT_QUERY;
+}
+function isMutationDefinition(e) {
+  return e.type === ENDPOINT_MUTATION;
+}
+function isInfiniteQueryDefinition(e) {
+  return e.type === ENDPOINT_INFINITEQUERY;
+}
+
+// src/query/tsHelpers.ts
+function safeAssign(target, ...args) {
+  return Object.assign(target, ...args);
+}
+
+// src/query/react/buildHooks.ts
+var import_toolkit = require("@reduxjs/toolkit");
+
+// src/query/react/reactImports.ts
+var import_react = require("react");
+
+// src/query/react/reactReduxImports.ts
+var import_react_redux = require("react-redux");
+
+// src/query/react/constants.ts
+var UNINITIALIZED_VALUE = Symbol();
+
+// src/query/react/useSerializedStableValue.ts
+function useStableQueryArgs(queryArgs) {
+  const cache = (0, import_react.useRef)(queryArgs);
+  const copy = (0, import_react.useMemo)(() => (0, import_query.copyWithStructuralSharing)(cache.current, queryArgs), [queryArgs]);
+  (0, import_react.useEffect)(() => {
+    if (cache.current !== copy) {
+      cache.current = copy;
+    }
+  }, [copy]);
+  return copy;
+}
+
+// src/query/react/useShallowStableValue.ts
+function useShallowStableValue(value) {
+  const cache = (0, import_react.useRef)(value);
+  (0, import_react.useEffect)(() => {
+    if (!(0, import_react_redux.shallowEqual)(cache.current, value)) {
+      cache.current = value;
+    }
+  }, [value]);
+  return (0, import_react_redux.shallowEqual)(cache.current, value) ? cache.current : value;
+}
+
+// src/query/react/buildHooks.ts
+var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
+var isDOM = /* @__PURE__ */ canUseDOM();
+var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
+var isReactNative = /* @__PURE__ */ isRunningInReactNative();
+var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? import_react.useLayoutEffect : import_react.useEffect;
+var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
+var noPendingQueryStateSelector = (selected) => {
+  if (selected.isUninitialized) {
+    return {
+      ...selected,
+      isUninitialized: false,
+      isFetching: true,
+      isLoading: selected.data !== void 0 ? 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: import_query.QueryStatus.pending
+    };
+  }
+  return selected;
+};
+function pick(obj, ...keys) {
+  const ret = {};
+  keys.forEach((key) => {
+    ret[key] = obj[key];
+  });
+  return ret;
+}
+var COMMON_HOOK_DEBUG_FIELDS = ["data", "status", "isLoading", "isSuccess", "isError", "error"];
+function buildHooks({
+  api,
+  moduleOptions: {
+    batch,
+    hooks: {
+      useDispatch,
+      useSelector,
+      useStore
+    },
+    unstable__sideEffectsInRender,
+    createSelector
+  },
+  serializeQueryArgs,
+  context
+}) {
+  const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : import_react.useEffect;
+  const unsubscribePromiseRef = (ref) => ref.current?.unsubscribe?.();
+  const endpointDefinitions = context.endpointDefinitions;
+  return {
+    buildQueryHooks,
+    buildInfiniteQueryHooks,
+    buildMutationHook,
+    usePrefetch
+  };
+  function queryStatePreSelector(currentState, lastResult, queryArgs) {
+    if (lastResult?.endpointName && currentState.isUninitialized) {
+      const {
+        endpointName
+      } = lastResult;
+      const endpointDefinition = endpointDefinitions[endpointName];
+      if (queryArgs !== import_query.skipToken && serializeQueryArgs({
+        queryArgs: lastResult.originalArgs,
+        endpointDefinition,
+        endpointName
+      }) === serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      })) lastResult = void 0;
+    }
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data;
+    if (data === void 0) data = currentState.data;
+    const hasData = data !== void 0;
+    const isFetching = currentState.isLoading;
+    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
+    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess
+    };
+  }
+  function infiniteQueryStatePreSelector(currentState, lastResult, queryArgs) {
+    if (lastResult?.endpointName && currentState.isUninitialized) {
+      const {
+        endpointName
+      } = lastResult;
+      const endpointDefinition = endpointDefinitions[endpointName];
+      if (queryArgs !== import_query.skipToken && serializeQueryArgs({
+        queryArgs: lastResult.originalArgs,
+        endpointDefinition,
+        endpointName
+      }) === serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      })) lastResult = void 0;
+    }
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data;
+    if (data === void 0) data = currentState.data;
+    const hasData = data !== void 0;
+    const isFetching = currentState.isLoading;
+    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
+    const isSuccess = currentState.isSuccess || isFetching && hasData;
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess
+    };
+  }
+  function usePrefetch(endpointName, defaultOptions) {
+    const dispatch = useDispatch();
+    const stableDefaultOptions = useShallowStableValue(defaultOptions);
+    return (0, import_react.useCallback)((arg, options) => dispatch(api.util.prefetch(endpointName, arg, {
+      ...stableDefaultOptions,
+      ...options
+    })), [endpointName, dispatch, stableDefaultOptions]);
+  }
+  function useQuerySubscriptionCommonImpl(endpointName, arg, {
+    refetchOnReconnect,
+    refetchOnFocus,
+    refetchOnMountOrArgChange,
+    skip = false,
+    pollingInterval = 0,
+    skipPollingIfUnfocused = false,
+    ...rest
+  } = {}) {
+    const {
+      initiate
+    } = api.endpoints[endpointName];
+    const dispatch = useDispatch();
+    const subscriptionSelectorsRef = (0, import_react.useRef)(void 0);
+    if (!subscriptionSelectorsRef.current) {
+      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
+      if (true) {
+        if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
+          throw new Error(false ? _formatProdErrorMessage(37) : `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;
+    }
+    const stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg);
+    const stableSubscriptionOptions = useShallowStableValue({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval,
+      skipPollingIfUnfocused
+    });
+    const initialPageParam = rest.initialPageParam;
+    const stableInitialPageParam = useShallowStableValue(initialPageParam);
+    const refetchCachedPages = rest.refetchCachedPages;
+    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);
+    const promiseRef = (0, import_react.useRef)(void 0);
+    let {
+      queryCacheKey,
+      requestId
+    } = promiseRef.current || {};
+    let currentRenderHasSubscription = false;
+    if (queryCacheKey && requestId) {
+      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
+    }
+    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== void 0;
+    usePossiblyImmediateEffect(() => {
+      if (subscriptionRemoved) {
+        promiseRef.current = void 0;
+      }
+    }, [subscriptionRemoved]);
+    usePossiblyImmediateEffect(() => {
+      const lastPromise = promiseRef.current;
+      if (typeof process !== "undefined" && false) {
+        console.log(subscriptionRemoved);
+      }
+      if (stableArg === import_query.skipToken) {
+        lastPromise?.unsubscribe();
+        promiseRef.current = void 0;
+        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;
+      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
+      }
+    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);
+    return [promiseRef, dispatch, initiate, stableSubscriptionOptions];
+  }
+  function buildUseQueryState(endpointName, preSelector) {
+    const useQueryState = (arg, {
+      skip = false,
+      selectFromResult
+    } = {}) => {
+      const {
+        select
+      } = api.endpoints[endpointName];
+      const stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg);
+      const lastValue = (0, import_react.useRef)(void 0);
+      const selectDefaultResult = (0, import_react.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),
+          (_, lastResult) => lastResult,
+          (_) => stableArg
+        ], preSelector, {
+          memoizeOptions: {
+            resultEqualityCheck: import_react_redux.shallowEqual
+          }
+        })
+      ), [select, stableArg]);
+      const querySelector = (0, import_react.useMemo)(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {
+        devModeChecks: {
+          identityFunctionCheck: "never"
+        }
+      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
+      const currentState = useSelector((state) => querySelector(state, lastValue.current), import_react_redux.shallowEqual);
+      const store = useStore();
+      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
+      useIsomorphicLayoutEffect(() => {
+        lastValue.current = newLastValue;
+      }, [newLastValue]);
+      return currentState;
+    };
+    return useQueryState;
+  }
+  function usePromiseRefUnsubscribeOnUnmount(promiseRef) {
+    (0, import_react.useEffect)(() => {
+      return () => {
+        unsubscribePromiseRef(promiseRef);
+        promiseRef.current = void 0;
+      };
+    }, [promiseRef]);
+  }
+  function refetchOrErrorIfUnmounted(promiseRef) {
+    if (!promiseRef.current) throw new Error(false ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
+    return promiseRef.current.refetch();
+  }
+  function buildQueryHooks(endpointName) {
+    const useQuerySubscription = (arg, options = {}) => {
+      const [promiseRef] = useQuerySubscriptionCommonImpl(endpointName, arg, options);
+      usePromiseRefUnsubscribeOnUnmount(promiseRef);
+      return (0, import_react.useMemo)(() => ({
+        /**
+         * A method to manually refetch data for the query
+         */
+        refetch: () => refetchOrErrorIfUnmounted(promiseRef)
+      }), [promiseRef]);
+    };
+    const useLazyQuerySubscription = ({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false
+    } = {}) => {
+      const {
+        initiate
+      } = api.endpoints[endpointName];
+      const dispatch = useDispatch();
+      const [arg, setArg] = (0, import_react.useState)(UNINITIALIZED_VALUE);
+      const promiseRef = (0, import_react.useRef)(void 0);
+      const stableSubscriptionOptions = useShallowStableValue({
+        refetchOnReconnect,
+        refetchOnFocus,
+        pollingInterval,
+        skipPollingIfUnfocused
+      });
+      usePossiblyImmediateEffect(() => {
+        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
+        if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+          promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);
+        }
+      }, [stableSubscriptionOptions]);
+      const subscriptionOptionsRef = (0, import_react.useRef)(stableSubscriptionOptions);
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions;
+      }, [stableSubscriptionOptions]);
+      const trigger = (0, import_react.useCallback)(function(arg2, preferCacheValue = false) {
+        let promise;
+        batch(() => {
+          unsubscribePromiseRef(promiseRef);
+          promiseRef.current = promise = dispatch(initiate(arg2, {
+            subscriptionOptions: subscriptionOptionsRef.current,
+            forceRefetch: !preferCacheValue
+          }));
+          setArg(arg2);
+        });
+        return promise;
+      }, [dispatch, initiate]);
+      const reset = (0, import_react.useCallback)(() => {
+        if (promiseRef.current?.queryCacheKey) {
+          dispatch(api.internalActions.removeQueryResult({
+            queryCacheKey: promiseRef.current?.queryCacheKey
+          }));
+        }
+      }, [dispatch]);
+      (0, import_react.useEffect)(() => {
+        return () => {
+          unsubscribePromiseRef(promiseRef);
+        };
+      }, []);
+      (0, import_react.useEffect)(() => {
+        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
+          trigger(arg, true);
+        }
+      }, [arg, trigger]);
+      return (0, import_react.useMemo)(() => [trigger, arg, {
+        reset
+      }], [trigger, arg, reset]);
+    };
+    const useQueryState = 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 = (0, import_react.useMemo)(() => ({
+          lastArg: arg
+        }), [arg]);
+        return (0, import_react.useMemo)(() => [trigger, {
+          ...queryStateResults,
+          reset
+        }, info], [trigger, queryStateResults, reset, info]);
+      },
+      useQuery(arg, options) {
+        const querySubscriptionResults = useQuerySubscription(arg, options);
+        const queryStateResults = useQueryState(arg, {
+          selectFromResult: arg === import_query.skipToken || options?.skip ? void 0 : noPendingQueryStateSelector,
+          ...options
+        });
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);
+        (0, import_react.useDebugValue)(debugValue);
+        return (0, import_react.useMemo)(() => ({
+          ...queryStateResults,
+          ...querySubscriptionResults
+        }), [queryStateResults, querySubscriptionResults]);
+      }
+    };
+  }
+  function buildInfiniteQueryHooks(endpointName) {
+    const useInfiniteQuerySubscription = (arg, options = {}) => {
+      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl(endpointName, arg, options);
+      const subscriptionOptionsRef = (0, import_react.useRef)(stableSubscriptionOptions);
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions;
+      }, [stableSubscriptionOptions]);
+      const hookRefetchCachedPages = options.refetchCachedPages;
+      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);
+      const trigger = (0, import_react.useCallback)(function(arg2, direction) {
+        let promise;
+        batch(() => {
+          unsubscribePromiseRef(promiseRef);
+          promiseRef.current = promise = dispatch(initiate(arg2, {
+            subscriptionOptions: subscriptionOptionsRef.current,
+            direction
+          }));
+        });
+        return promise;
+      }, [promiseRef, dispatch, initiate]);
+      usePromiseRefUnsubscribeOnUnmount(promiseRef);
+      const stableArg = useStableQueryArgs(options.skip ? import_query.skipToken : arg);
+      const refetch = (0, import_react.useCallback)((options2) => {
+        if (!promiseRef.current) throw new Error(false ? _formatProdErrorMessage3(38) : "Cannot refetch a query that has not been started yet.");
+        const mergedOptions = {
+          refetchCachedPages: options2?.refetchCachedPages ?? stableHookRefetchCachedPages
+        };
+        return promiseRef.current.refetch(mergedOptions);
+      }, [promiseRef, stableHookRefetchCachedPages]);
+      return (0, import_react.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 = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);
+    return {
+      useInfiniteQueryState,
+      useInfiniteQuerySubscription,
+      useInfiniteQuery(arg, options) {
+        const {
+          refetch,
+          fetchNextPage,
+          fetchPreviousPage
+        } = useInfiniteQuerySubscription(arg, options);
+        const queryStateResults = useInfiniteQueryState(arg, {
+          selectFromResult: arg === import_query.skipToken || options?.skip ? void 0 : noPendingQueryStateSelector,
+          ...options
+        });
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, "hasNextPage", "hasPreviousPage");
+        (0, import_react.useDebugValue)(debugValue);
+        return (0, import_react.useMemo)(() => ({
+          ...queryStateResults,
+          fetchNextPage,
+          fetchPreviousPage,
+          refetch
+        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);
+      }
+    };
+  }
+  function buildMutationHook(name) {
+    return ({
+      selectFromResult,
+      fixedCacheKey
+    } = {}) => {
+      const {
+        select,
+        initiate
+      } = api.endpoints[name];
+      const dispatch = useDispatch();
+      const [promise, setPromise] = (0, import_react.useState)();
+      (0, import_react.useEffect)(() => () => {
+        if (!promise?.arg.fixedCacheKey) {
+          promise?.reset();
+        }
+      }, [promise]);
+      const triggerMutation = (0, import_react.useCallback)(function(arg) {
+        const promise2 = dispatch(initiate(arg, {
+          fixedCacheKey
+        }));
+        setPromise(promise2);
+        return promise2;
+      }, [dispatch, initiate, fixedCacheKey]);
+      const {
+        requestId
+      } = promise || {};
+      const selectDefaultResult = (0, import_react.useMemo)(() => select({
+        fixedCacheKey,
+        requestId: promise?.requestId
+      }), [fixedCacheKey, promise, select]);
+      const mutationSelector = (0, import_react.useMemo)(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
+      const currentState = useSelector(mutationSelector, import_react_redux.shallowEqual);
+      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : void 0;
+      const reset = (0, import_react.useCallback)(() => {
+        batch(() => {
+          if (promise) {
+            setPromise(void 0);
+          }
+          if (fixedCacheKey) {
+            dispatch(api.internalActions.removeMutationResult({
+              requestId,
+              fixedCacheKey
+            }));
+          }
+        });
+      }, [dispatch, fixedCacheKey, promise, requestId]);
+      const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, "endpointName");
+      (0, import_react.useDebugValue)(debugValue);
+      const finalState = (0, import_react.useMemo)(() => ({
+        ...currentState,
+        originalArgs,
+        reset
+      }), [currentState, originalArgs, reset]);
+      return (0, import_react.useMemo)(() => [triggerMutation, finalState], [triggerMutation, finalState]);
+    };
+  }
+}
+
+// src/query/react/module.ts
+var reactHooksModuleName = /* @__PURE__ */ Symbol();
+var reactHooksModule = ({
+  batch = import_react_redux2.batch,
+  hooks = {
+    useDispatch: import_react_redux2.useDispatch,
+    useSelector: import_react_redux2.useSelector,
+    useStore: import_react_redux2.useStore
+  },
+  createSelector = import_reselect.createSelector,
+  unstable__sideEffectsInRender = false,
+  ...rest
+} = {}) => {
+  if (true) {
+    const hookNames = ["useDispatch", "useSelector", "useStore"];
+    let warned = false;
+    for (const hookName of hookNames) {
+      if (countObjectKeys(rest) > 0) {
+        if (rest[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;
+          }
+        }
+        hooks[hookName] = rest[hookName];
+      }
+      if (typeof hooks[hookName] !== "function") {
+        throw new Error(false ? _formatProdErrorMessage4(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
+Hook ${hookName} was either not provided or not a function.`);
+      }
+    }
+  }
+  return {
+    name: reactHooksModuleName,
+    init(api, {
+      serializeQueryArgs
+    }, context) {
+      const anyApi = api;
+      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[`use${capitalize(endpointName)}Query`] = useQuery;
+            api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
+          }
+          if (isMutationDefinition(definition)) {
+            const useMutation = buildMutationHook(endpointName);
+            safeAssign(anyApi.endpoints[endpointName], {
+              useMutation
+            });
+            api[`use${capitalize(endpointName)}Mutation`] = useMutation;
+          } else if (isInfiniteQueryDefinition(definition)) {
+            const {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState
+            } = buildInfiniteQueryHooks(endpointName);
+            safeAssign(anyApi.endpoints[endpointName], {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState
+            });
+            api[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;
+          }
+        }
+      };
+    }
+  };
+};
+
+// src/query/react/index.ts
+__reExport(react_exports, require("@reduxjs/toolkit/query"), module.exports);
+
+// src/query/react/ApiProvider.tsx
+var import_toolkit3 = require("@reduxjs/toolkit");
+var React = __toESM(require("react"));
+function ApiProvider(props) {
+  const context = props.context || import_react_redux.ReactReduxContext;
+  const existingContext = (0, import_react.useContext)(context);
+  if (existingContext) {
+    throw new Error(false ? _formatProdErrorMessage5(35) : "Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.");
+  }
+  const [store] = React.useState(() => (0, import_toolkit3.configureStore)({
+    reducer: {
+      [props.api.reducerPath]: props.api.reducer
+    },
+    middleware: (gDM) => gDM().concat(props.api.middleware)
+  }));
+  (0, import_react.useEffect)(() => props.setupListeners === false ? void 0 : (0, import_query.setupListeners)(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
+  return /* @__PURE__ */ React.createElement(import_react_redux.Provider, { store, context }, props.children);
+}
+
+// src/query/react/index.ts
+var createApi = /* @__PURE__ */ (0, import_query.buildCreateApi)((0, import_query.coreModule)(), reactHooksModule());
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+  ApiProvider,
+  UNINITIALIZED_VALUE,
+  createApi,
+  reactHooksModule,
+  reactHooksModuleName,
+  ...require("@reduxjs/toolkit/query")
+});
+//# sourceMappingURL=rtk-query-react.development.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.development.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../../src/query/react/index.ts","../../../../src/query/react/rtkqImports.ts","../../../../src/query/react/module.ts","../../../../src/query/utils/capitalize.ts","../../../../src/query/utils/countObjectKeys.ts","../../../../src/query/endpointDefinitions.ts","../../../../src/query/tsHelpers.ts","../../../../src/query/react/buildHooks.ts","../../../../src/query/react/reactImports.ts","../../../../src/query/react/reactReduxImports.ts","../../../../src/query/react/constants.ts","../../../../src/query/react/useSerializedStableValue.ts","../../../../src/query/react/useShallowStableValue.ts","../../../../src/query/react/ApiProvider.tsx"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nimport { buildCreateApi, coreModule } from './rtkqImports';\nimport { reactHooksModule, reactHooksModuleName } from './module';\nexport * from '@reduxjs/toolkit/query';\nexport { ApiProvider } from './ApiProvider';\nconst createApi = /* @__PURE__ */buildCreateApi(coreModule(), reactHooksModule());\nexport 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';\nexport { UNINITIALIZED_VALUE } from './constants';\nexport { createApi, reactHooksModule, reactHooksModuleName };","export { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from '@reduxjs/toolkit/query';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Api, BaseQueryFn, EndpointDefinitions, InfiniteQueryDefinition, Module, MutationDefinition, PrefetchOptions, QueryArgFrom, QueryDefinition, QueryKeys } from '@reduxjs/toolkit/query';\nimport { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from 'react-redux';\nimport type { CreateSelectorFunction } from 'reselect';\nimport { createSelector as _createSelector } from 'reselect';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { safeAssign } from '../tsHelpers';\nimport { capitalize, countObjectKeys } from '../utils';\nimport type { InfiniteQueryHooks, MutationHooks, QueryHooks } from './buildHooks';\nimport { buildHooks } from './buildHooks';\nimport type { HooksWithUniqueNames } from './namedHooks';\nexport const reactHooksModuleName = /* @__PURE__ */Symbol();\nexport type ReactHooksModule = typeof reactHooksModuleName;\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  ReducerPath extends string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  TagTypes extends string> {\n    [reactHooksModuleName]: {\n      /**\n       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n       */\n      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 };\n      /**\n       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n       */\n      usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;\n    } & HooksWithUniqueNames<Definitions>;\n  }\n}\ntype RR = typeof import('react-redux');\nexport interface ReactHooksModuleOptions {\n  /**\n   * The hooks from React Redux to be used\n   */\n  hooks?: {\n    /**\n     * The version of the `useDispatch` hook to be used\n     */\n    useDispatch: RR['useDispatch'];\n    /**\n     * The version of the `useSelector` hook to be used\n     */\n    useSelector: RR['useSelector'];\n    /**\n     * The version of the `useStore` hook to be used\n     */\n    useStore: RR['useStore'];\n  };\n  /**\n   * The version of the `batchedUpdates` function to be used\n   */\n  batch?: RR['batch'];\n  /**\n   * Enables performing asynchronous tasks immediately within a render.\n   *\n   * @example\n   *\n   * ```ts\n   * import {\n   *   buildCreateApi,\n   *   coreModule,\n   *   reactHooksModule\n   * } from '@reduxjs/toolkit/query/react'\n   *\n   * const createApi = buildCreateApi(\n   *   coreModule(),\n   *   reactHooksModule({ unstable__sideEffectsInRender: true })\n   * )\n   * ```\n   */\n  unstable__sideEffectsInRender?: boolean;\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n *  @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n  batch = rrBatch,\n  hooks = {\n    useDispatch: rrUseDispatch,\n    useSelector: rrUseSelector,\n    useStore: rrUseStore\n  },\n  createSelector = _createSelector,\n  unstable__sideEffectsInRender = false,\n  ...rest\n}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {\n  if (process.env.NODE_ENV !== 'production') {\n    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const;\n    let warned = false;\n    for (const hookName of hookNames) {\n      // warn for old hook options\n      if (countObjectKeys(rest) > 0) {\n        if ((rest as Partial<typeof hooks>)[hookName]) {\n          if (!warned) {\n            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 } })`');\n            warned = true;\n          }\n        }\n        // migrate\n        // @ts-ignore\n        hooks[hookName] = rest[hookName];\n      }\n      // then make sure we have them all\n      if (typeof hooks[hookName] !== 'function') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(36) : `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.`);\n      }\n    }\n  }\n  return {\n    name: reactHooksModuleName,\n    init(api, {\n      serializeQueryArgs\n    }, context) {\n      const anyApi = api as any as Api<any, Record<string, any>, any, any, ReactHooksModule>;\n      const {\n        buildQueryHooks,\n        buildInfiniteQueryHooks,\n        buildMutationHook,\n        usePrefetch\n      } = buildHooks({\n        api,\n        moduleOptions: {\n          batch,\n          hooks,\n          unstable__sideEffectsInRender,\n          createSelector\n        },\n        serializeQueryArgs,\n        context\n      });\n      safeAssign(anyApi, {\n        usePrefetch\n      });\n      safeAssign(context, {\n        batch\n      });\n      return {\n        injectEndpoint(endpointName, definition) {\n          if (isQueryDefinition(definition)) {\n            const {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            } = buildQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            });\n            (api as any)[`use${capitalize(endpointName)}Query`] = useQuery;\n            (api as any)[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;\n          }\n          if (isMutationDefinition(definition)) {\n            const useMutation = buildMutationHook(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useMutation\n            });\n            (api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation;\n          } else if (isInfiniteQueryDefinition(definition)) {\n            const {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            } = buildInfiniteQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            });\n            (api as any)[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;\n          }\n        }\n      };\n    }\n  };\n};","export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase());\n}","// Fast method for counting an object's keys\n// without resorting to `Object.keys(obj).length\n// Will this make a big difference in perf? Probably not\n// But we can save a few allocations.\n\nexport function countObjectKeys(obj: Record<any, any>) {\n  let count = 0;\n  for (const _key in obj) {\n    count++;\n  }\n  return count;\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Selector, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport 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';\nimport { QueryStatus, skipToken } from './rtkqImports';\nimport type { DependencyList } from 'react';\nimport { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/index';\nimport type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index';\nimport type { UninitializedValue } from './constants';\nimport { UNINITIALIZED_VALUE } from './constants';\nimport type { ReactHooksModuleOptions } from './module';\nimport { useStableQueryArgs } from './useSerializedStableValue';\nimport { useShallowStableValue } from './useShallowStableValue';\nimport type { InfiniteQueryDirection } from '../core/apiState';\nimport { isInfiniteQueryDefinition } from '../endpointDefinitions';\nimport type { StartInfiniteQueryActionCreator } from '../core/buildInitiate';\n\n// Copy-pasted from React-Redux\nconst canUseDOM = () => !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nconst isDOM = /* @__PURE__ */canUseDOM();\n\n// Under React Native, we know that we always want to use useLayoutEffect\n\nconst isRunningInReactNative = () => typeof navigator !== 'undefined' && navigator.product === 'ReactNative';\nconst isReactNative = /* @__PURE__ */isRunningInReactNative();\nconst getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;\nexport const useIsomorphicLayoutEffect = /* @__PURE__ */getUseIsomorphicLayoutEffect();\nexport type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  useQuery: UseQuery<Definition>;\n  useLazyQuery: UseLazyQuery<Definition>;\n  useQuerySubscription: UseQuerySubscription<Definition>;\n  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;\n  useQueryState: UseQueryState<Definition>;\n};\nexport type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  useInfiniteQuery: UseInfiniteQuery<Definition>;\n  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;\n  useInfiniteQueryState: UseInfiniteQueryState<Definition>;\n};\nexport type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  useMutation: UseMutation<Definition>;\n};\n\n/**\n * 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.\n *\n * 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.\n *\n * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuery` hook in userland code.\n */\nexport type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;\nexport type UseQuerySubscriptionOptions = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n};\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;\nexport type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {\n  lastArg: QueryArgFrom<D>;\n};\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - 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\n *\n * #### Note\n *\n * 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.\n */\nexport 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>];\nexport type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useLazyQuery` hook in userland code.\n */\nexport type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\nexport type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;\n};\nexport type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - 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\n */\nexport type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, {\n  reset: () => void;\n}];\nexport type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   title: string\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * type SelectedResult = Pick<PostsApiResponse, 'posts'>\n *\n * const postsApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, QueryArgument>({\n *       query: (limit = 5) => `?limit=${limit}&select=title`,\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = postsApiSlice\n *\n * function PostById({ id }: { id: number }) {\n *   const { post } = useGetPostsQuery(undefined, {\n *     selectFromResult: (state) => ({\n *       post: state.data?.posts.find((post) => post.id === id),\n *     }),\n *   })\n *\n *   return <li>{post?.title}</li>\n * }\n *\n * const EMPTY_ARRAY: Post[] = []\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n *\n * function PostsList() {\n *   const { posts } = useGetPostsQuery(undefined, {\n *     selectFromResult: typedSelectFromResult,\n *   })\n *\n *   return (\n *     <div>\n *       <ul>\n *         {posts.map((post) => (\n *           <PostById key={post.id} id={post.id} />\n *         ))}\n *       </ul>\n *     </div>\n *   )\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.3.0\n * @public\n */\nexport 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>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: QueryStateSelector<R, D>;\n};\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * <caption>#### __Create a `useQuery` hook with default options__</caption>\n *\n * ```ts\n * import type {\n *   SubscriptionOptions,\n *   TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   name: string\n * }\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   tagTypes: ['Post'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<Post[], void>({\n *       query: () => 'posts',\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = api\n *\n * export const useGetPostsQueryWithDefaults = <\n *   SelectedResult extends Record<string, any>,\n * >(\n *   overrideOptions: TypedUseQueryStateOptions<\n *     Post[],\n *     void,\n *     ReturnType<typeof fetchBaseQuery>,\n *     SelectedResult\n *   > &\n *     SubscriptionOptions,\n * ) =>\n *   useGetPostsQuery(undefined, {\n *     // Insert default options here\n *\n *     refetchOnMountOrArgChange: true,\n *     refetchOnFocus: true,\n *     ...overrideOptions,\n *   })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.2.8\n * @public\n */\nexport 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>;\nexport type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;\ntype UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: ResultTypeFrom<D>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n};\ntype UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}>;\ntype UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n}>;\ntype UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n  currentData: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isError: true;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;\ntype UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;\n};\nexport type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  initialPageParam?: PageParamFrom<D>;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   *\n   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).\n   * It can be overridden on a per-call basis using the `refetch()` method.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  refetch: (options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>) => InfiniteQueryActionCreatorResult<D>;\n  trigger: LazyInfiniteQueryTrigger<D>;\n  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;\nexport 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>>;\n\n/**\n * 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.\n *\n * 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.\n *\n *  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.\n *\n * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.\n *\n * 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.\n *\n * 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.\n *\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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'>;\nexport type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;\nexport type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;\nexport 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>;\nexport type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: InfiniteQueryStateSelector<R, D>;\n};\nexport 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>;\nexport type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;\nexport 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>;\ntype UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n};\ntype UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n} | ({\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({\n  isError: true;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;\nexport type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  selectFromResult?: MutationStateSelector<R, D>;\n  fixedCacheKey?: string;\n};\nexport type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {\n  originalArgs?: QueryArgFrom<D>;\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\n\n/**\n * 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.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>];\nexport type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {\n  /**\n   * Triggers the mutation and returns a Promise.\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;\n};\nexport type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector<any, any> = selected => {\n  if (selected.isUninitialized) {\n    return {\n      ...selected,\n      isUninitialized: false,\n      isFetching: true,\n      isLoading: selected.data !== undefined ? false : true,\n      // This is the one place where we still have to use `QueryStatus` as an enum,\n      // since it's the only reference in the React package and not in the core.\n      status: QueryStatus.pending\n    } as any;\n  }\n  return selected;\n};\nfunction pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {\n  const ret: any = {};\n  keys.forEach(key => {\n    ret[key] = obj[key];\n  });\n  return ret;\n}\nconst COMMON_HOOK_DEBUG_FIELDS = ['data', 'status', 'isLoading', 'isSuccess', 'isError', 'error'] as const;\ntype GenericPrefetchThunk = (endpointName: any, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, UnknownAction>;\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks<Definitions extends EndpointDefinitions>({\n  api,\n  moduleOptions: {\n    batch,\n    hooks: {\n      useDispatch,\n      useSelector,\n      useStore\n    },\n    unstable__sideEffectsInRender,\n    createSelector\n  },\n  serializeQueryArgs,\n  context\n}: {\n  api: Api<any, Definitions, any, any, CoreModule>;\n  moduleOptions: Required<ReactHooksModuleOptions>;\n  serializeQueryArgs: SerializeQueryArgs<any>;\n  context: ApiContext<Definitions>;\n}) {\n  const usePossiblyImmediateEffect: (effect: () => void | undefined, deps?: DependencyList) => void = unstable__sideEffectsInRender ? cb => cb() : useEffect;\n  type UnsubscribePromiseRef = React.RefObject<{\n    unsubscribe?: () => void;\n  } | undefined>;\n  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) => ref.current?.unsubscribe?.();\n  const endpointDefinitions = context.endpointDefinitions;\n  return {\n    buildQueryHooks,\n    buildInfiniteQueryHooks,\n    buildMutationHook,\n    usePrefetch\n  };\n  function queryStatePreSelector(currentState: QueryResultSelectorResult<any>, lastResult: UseQueryStateDefaultResult<any> | undefined, queryArgs: any): UseQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n\n    // isSuccess = true when data is present and we're not refetching after an error.\n    // That includes cases where the _current_ item is either actively\n    // fetching or about to fetch due to an uninitialized entry.\n    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseQueryStateDefaultResult<any>;\n  }\n  function infiniteQueryStatePreSelector(currentState: InfiniteQueryResultSelectorResult<any>, lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined, queryArgs: any): UseInfiniteQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n    // isSuccess = true when data is present\n    const isSuccess = currentState.isSuccess || isFetching && hasData;\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseInfiniteQueryStateDefaultResult<any>;\n  }\n  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions) {\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n    const stableDefaultOptions = useShallowStableValue(defaultOptions);\n    return useCallback((arg: any, options?: PrefetchOptions) => dispatch((api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n      ...stableDefaultOptions,\n      ...options\n    })), [endpointName, dispatch, stableDefaultOptions]);\n  }\n  function useQuerySubscriptionCommonImpl<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(endpointName: string, arg: unknown | SkipToken, {\n    refetchOnReconnect,\n    refetchOnFocus,\n    refetchOnMountOrArgChange,\n    skip = false,\n    pollingInterval = 0,\n    skipPollingIfUnfocused = false,\n    ...rest\n  }: UseQuerySubscriptionOptions = {}) {\n    const {\n      initiate\n    } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n\n    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.\n    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(undefined);\n    if (!subscriptionSelectorsRef.current) {\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n    You must add the middleware for RTK-Query to function correctly!`);\n        }\n      }\n      subscriptionSelectorsRef.current = returnedValue as unknown as SubscriptionSelectors;\n    }\n    const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n    const stableSubscriptionOptions = useShallowStableValue({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval,\n      skipPollingIfUnfocused\n    });\n    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>).initialPageParam;\n    const stableInitialPageParam = useShallowStableValue(initialPageParam);\n    const refetchCachedPages = (rest as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);\n\n    /**\n     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n     */\n    const promiseRef = useRef<T | undefined>(undefined);\n    let {\n      queryCacheKey,\n      requestId\n    } = promiseRef.current || {};\n\n    // HACK We've saved the middleware subscription lookup callbacks into a ref,\n    // so we can directly check here if the subscription exists for this query.\n    let currentRenderHasSubscription = false;\n    if (queryCacheKey && requestId) {\n      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);\n    }\n    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== undefined;\n    usePossiblyImmediateEffect((): void | undefined => {\n      if (subscriptionRemoved) {\n        promiseRef.current = undefined;\n      }\n    }, [subscriptionRemoved]);\n    usePossiblyImmediateEffect((): void | undefined => {\n      const lastPromise = promiseRef.current;\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {\n        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n        console.log(subscriptionRemoved);\n      }\n      if (stableArg === skipToken) {\n        lastPromise?.unsubscribe();\n        promiseRef.current = undefined;\n        return;\n      }\n      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n      if (!lastPromise || lastPromise.arg !== stableArg) {\n        lastPromise?.unsubscribe();\n        const promise = dispatch(initiate(stableArg, {\n          subscriptionOptions: stableSubscriptionOptions,\n          forceRefetch: refetchOnMountOrArgChange,\n          ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {\n            initialPageParam: stableInitialPageParam,\n            refetchCachedPages: stableRefetchCachedPages\n          } : {})\n        }));\n        promiseRef.current = promise as T;\n      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\n      }\n    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);\n    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const;\n  }\n  function buildUseQueryState(endpointName: string, preSelector: typeof queryStatePreSelector | typeof infiniteQueryStatePreSelector) {\n    const useQueryState = (arg: any, {\n      skip = false,\n      selectFromResult\n    }: UseQueryStateOptions<any, any> | UseInfiniteQueryStateOptions<any, any> = {}) => {\n      const {\n        select\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n      type ApiRootState = Parameters<ReturnType<typeof select>>[0];\n      const lastValue = useRef<any>(undefined);\n      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(() =>\n      // Normally ts-ignores are bad and should be avoided, but we're\n      // already casting this selector to be `Selector<any>` anyway,\n      // so the inconsistencies don't matter here\n      // @ts-ignore\n      createSelector([\n      // @ts-ignore\n      select(stableArg), (_: ApiRootState, lastResult: any) => lastResult, (_: ApiRootState) => stableArg], preSelector, {\n        memoizeOptions: {\n          resultEqualityCheck: shallowEqual\n        }\n      }), [select, stableArg]);\n      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {\n        devModeChecks: {\n          identityFunctionCheck: 'never'\n        }\n      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);\n      const currentState = useSelector((state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current), shallowEqual);\n      const store = useStore<RootState<Definitions, any, any>>();\n      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);\n      useIsomorphicLayoutEffect(() => {\n        lastValue.current = newLastValue;\n      }, [newLastValue]);\n      return currentState;\n    };\n    return useQueryState;\n  }\n  function usePromiseRefUnsubscribeOnUnmount(promiseRef: UnsubscribePromiseRef) {\n    useEffect(() => {\n      return () => {\n        unsubscribePromiseRef(promiseRef)\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        ;\n        (promiseRef.current as any) = undefined;\n      };\n    }, [promiseRef]);\n  }\n  function refetchOrErrorIfUnmounted<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(promiseRef: React.RefObject<T | undefined>): T {\n    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(38) : 'Cannot refetch a query that has not been started yet.');\n    return promiseRef.current.refetch() as T;\n  }\n  function buildQueryHooks(endpointName: string): QueryHooks<any> {\n    const useQuerySubscription: UseQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef] = useQuerySubscriptionCommonImpl<QueryActionCreatorResult<any>>(endpointName, arg, options);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      return useMemo(() => ({\n        /**\n         * A method to manually refetch data for the query\n         */\n        refetch: () => refetchOrErrorIfUnmounted(promiseRef)\n      }), [promiseRef]);\n    };\n    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false\n    } = {}) => {\n      const {\n        initiate\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE);\n\n      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n      /**\n       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n       */\n      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(undefined);\n      const stableSubscriptionOptions = useShallowStableValue({\n        refetchOnReconnect,\n        refetchOnFocus,\n        pollingInterval,\n        skipPollingIfUnfocused\n      });\n      usePossiblyImmediateEffect(() => {\n        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n        if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n          promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);\n        }\n      }, [stableSubscriptionOptions]);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n      const trigger = useCallback(function (arg: any, preferCacheValue = false) {\n        let promise: QueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch(initiate(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            forceRefetch: !preferCacheValue\n          }));\n          setArg(arg);\n        });\n        return promise!;\n      }, [dispatch, initiate]);\n      const reset = useCallback(() => {\n        if (promiseRef.current?.queryCacheKey) {\n          dispatch(api.internalActions.removeQueryResult({\n            queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey\n          }));\n        }\n      }, [dispatch]);\n\n      /* cleanup on unmount */\n      useEffect(() => {\n        return () => {\n          unsubscribePromiseRef(promiseRef);\n        };\n      }, []);\n\n      /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n      useEffect(() => {\n        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n          trigger(arg, true);\n        }\n      }, [arg, trigger]);\n      return useMemo(() => [trigger, arg, {\n        reset\n      }] as const, [trigger, arg, reset]);\n    };\n    const useQueryState: UseQueryState<any> = buildUseQueryState(endpointName, queryStatePreSelector);\n    return {\n      useQueryState,\n      useQuerySubscription,\n      useLazyQuerySubscription,\n      useLazyQuery(options) {\n        const [trigger, arg, {\n          reset\n        }] = useLazyQuerySubscription(options);\n        const queryStateResults = useQueryState(arg, {\n          ...options,\n          skip: arg === UNINITIALIZED_VALUE\n        });\n        const info = useMemo(() => ({\n          lastArg: arg\n        }), [arg]);\n        return useMemo(() => [trigger, {\n          ...queryStateResults,\n          reset\n        }, info], [trigger, queryStateResults, reset, info]);\n      },\n      useQuery(arg, options) {\n        const querySubscriptionResults = useQuerySubscription(arg, options);\n        const queryStateResults = useQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          ...querySubscriptionResults\n        }), [queryStateResults, querySubscriptionResults]);\n      }\n    };\n  }\n  function buildInfiniteQueryHooks(endpointName: string): InfiniteQueryHooks<any> {\n    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(endpointName, arg, options);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n\n      // Extract and stabilize the hook-level refetchCachedPages option\n      const hookRefetchCachedPages = (options as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);\n      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(function (arg: unknown, direction: 'forward' | 'backward') {\n        let promise: InfiniteQueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch((initiate as StartInfiniteQueryActionCreator<any>)(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            direction\n          }));\n        });\n        return promise!;\n      }, [promiseRef, dispatch, initiate]);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);\n      const refetch = useCallback((options?: Pick<UseInfiniteQuerySubscriptionOptions<any>, 'refetchCachedPages'>) => {\n        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(38) : 'Cannot refetch a query that has not been started yet.');\n        // Merge per-call options with hook-level default\n        const mergedOptions = {\n          refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages\n        };\n        return promiseRef.current.refetch(mergedOptions);\n      }, [promiseRef, stableHookRefetchCachedPages]);\n      return useMemo(() => {\n        const fetchNextPage = () => {\n          return trigger(stableArg, 'forward');\n        };\n        const fetchPreviousPage = () => {\n          return trigger(stableArg, 'backward');\n        };\n        return {\n          trigger,\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        };\n      }, [refetch, trigger, stableArg]);\n    };\n    const useInfiniteQueryState: UseInfiniteQueryState<any> = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);\n    return {\n      useInfiniteQueryState,\n      useInfiniteQuerySubscription,\n      useInfiniteQuery(arg, options) {\n        const {\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        } = useInfiniteQuerySubscription(arg, options);\n        const queryStateResults = useInfiniteQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, 'hasNextPage', 'hasPreviousPage');\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          fetchNextPage,\n          fetchPreviousPage,\n          refetch\n        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);\n      }\n    };\n  }\n  function buildMutationHook(name: string): UseMutation<any> {\n    return ({\n      selectFromResult,\n      fixedCacheKey\n    } = {}) => {\n      const {\n        select,\n        initiate\n      } = api.endpoints[name] as ApiEndpointMutation<MutationDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>();\n      useEffect(() => () => {\n        if (!promise?.arg.fixedCacheKey) {\n          promise?.reset();\n        }\n      }, [promise]);\n      const triggerMutation = useCallback(function (arg: Parameters<typeof initiate>['0']) {\n        const promise = dispatch(initiate(arg, {\n          fixedCacheKey\n        }));\n        setPromise(promise);\n        return promise;\n      }, [dispatch, initiate, fixedCacheKey]);\n      const {\n        requestId\n      } = promise || {};\n      const selectDefaultResult = useMemo(() => select({\n        fixedCacheKey,\n        requestId: promise?.requestId\n      }), [fixedCacheKey, promise, select]);\n      const mutationSelector = useMemo((): Selector<RootState<Definitions, any, any>, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);\n      const currentState = useSelector(mutationSelector, shallowEqual);\n      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;\n      const reset = useCallback(() => {\n        batch(() => {\n          if (promise) {\n            setPromise(undefined);\n          }\n          if (fixedCacheKey) {\n            dispatch(api.internalActions.removeMutationResult({\n              requestId,\n              fixedCacheKey\n            }));\n          }\n        });\n      }, [dispatch, fixedCacheKey, promise, requestId]);\n      const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, 'endpointName');\n      useDebugValue(debugValue);\n      const finalState = useMemo(() => ({\n        ...currentState,\n        originalArgs,\n        reset\n      }), [currentState, originalArgs, reset]);\n      return useMemo(() => [triggerMutation, finalState] as const, [triggerMutation, finalState]);\n    };\n  }\n}","export { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from 'react';","export { shallowEqual, Provider, ReactReduxContext } from 'react-redux';","export const UNINITIALIZED_VALUE = Symbol();\nexport type UninitializedValue = typeof UNINITIALIZED_VALUE;","import { useEffect, useRef, useMemo } from './reactImports';\nimport { copyWithStructuralSharing } from './rtkqImports';\nexport function useStableQueryArgs<T>(queryArgs: T) {\n  const cache = useRef(queryArgs);\n  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);\n  useEffect(() => {\n    if (cache.current !== copy) {\n      cache.current = copy;\n    }\n  }, [copy]);\n  return copy;\n}","import { useEffect, useRef } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nexport function useShallowStableValue<T>(value: T) {\n  const cache = useRef(value);\n  useEffect(() => {\n    if (!shallowEqual(cache.current, value)) {\n      cache.current = value;\n    }\n  }, [value]);\n  return shallowEqual(cache.current, value) ? cache.current : value;\n}","import { configureStore, formatProdErrorMessage as _formatProdErrorMessage } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport { useContext, useEffect } from './reactImports';\nimport * as React from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { Provider, ReactReduxContext } from './reactReduxImports';\nimport { setupListeners } from './rtkqImports';\nimport type { Api } from '@reduxjs/toolkit/query';\n\n/**\n * Can be used as a `Provider` if you **do not already have a Redux store**.\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Basic usage - wrap your App with ApiProvider\"\n * import * as React from 'react';\n * import { ApiProvider } from '@reduxjs/toolkit/query/react';\n * import { Pokemon } from './features/Pokemon';\n *\n * function App() {\n *   return (\n *     <ApiProvider api={api}>\n *       <Pokemon />\n *     </ApiProvider>\n *   );\n * }\n * ```\n *\n * @remarks\n * Using this together with an existing redux store, both will\n * conflict with each other - please use the traditional redux setup\n * in that case.\n */\nexport function ApiProvider(props: {\n  children: any;\n  api: Api<any, {}, any, any>;\n  setupListeners?: Parameters<typeof setupListeners>[1] | false;\n  context?: Context<ReactReduxContextValue | null>;\n}) {\n  const context = props.context || ReactReduxContext;\n  const existingContext = useContext(context);\n  if (existingContext) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(35) : 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.');\n  }\n  const [store] = React.useState(() => configureStore({\n    reducer: {\n      [props.api.reducerPath]: props.api.reducer\n    },\n    middleware: gDM => gDM().concat(props.api.middleware)\n  }));\n  // Adds the event listeners for online/offline/focus/etc\n  useEffect((): undefined | (() => void) => props.setupListeners === false ? undefined : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);\n  return <Provider store={store} context={context}>\n      {props.children}\n    </Provider>;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAA8G;;;ACA9G,IAAAA,kBAAkE;AAElE,IAAAC,sBAAqH;AAErH,sBAAkD;;;ACJ3C,SAAS,WAAW,KAAa;AACtC,SAAO,IAAI,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,EAAE,YAAY,CAAC;AACjD;;;ACGO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,QAAQ;AACZ,aAAW,QAAQ,KAAK;AACtB;AAAA,EACF;AACA,SAAO;AACT;;;AC8XO,IAAM,iBAAiB;AACvB,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AA+c/B,SAAS,kBAAkB,GAA8G;AAC9I,SAAO,EAAE,SAAS;AACpB;AACO,SAAS,qBAAqB,GAAiH;AACpJ,SAAO,EAAE,SAAS;AACpB;AACO,SAAS,0BAA0B,GAA2H;AACnK,SAAO,EAAE,SAAS;AACpB;;;AC91BO,SAAS,WAA6B,WAAc,MAAqC;AAC9F,SAAO,OAAO,OAAO,QAAQ,GAAG,IAAI;AAC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A,UAC3D,WAAW,0BAA0B,UAAU,GAAG;AAChD,kBAAM;AAAA,cACJ;AAAA,cACA;AAAA,cACA;AAAA,YACF,IAAI,wBAAwB,YAAY;AACxC,uBAAW,OAAO,UAAU,YAAY,GAAG;AAAA,cACzC;AAAA,cACA;AAAA,cACA;AAAA,YACF,CAAC;AACD,YAAC,IAAY,MAAM,WAAW,YAAY,CAAC,eAAe,IAAI;AAAA,UAChE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AFxMA,0BAAc,mCALd;;;AaAA,IAAAC,kBAAkF;AAGlF,YAAuB;AA8BhB,SAAS,YAAY,OAKzB;AACD,QAAM,UAAU,MAAM,WAAW;AACjC,QAAM,sBAAkB,yBAAW,OAAO;AAC1C,MAAI,iBAAiB;AACnB,UAAM,IAAI,MAAM,QAAwCC,yBAAwB,EAAE,IAAI,8GAA8G;AAAA,EACtM;AACA,QAAM,CAAC,KAAK,IAAU,eAAS,UAAM,gCAAe;AAAA,IAClD,SAAS;AAAA,MACP,CAAC,MAAM,IAAI,WAAW,GAAG,MAAM,IAAI;AAAA,IACrC;AAAA,IACA,YAAY,SAAO,IAAI,EAAE,OAAO,MAAM,IAAI,UAAU;AAAA,EACtD,CAAC,CAAC;AAEF,8BAAU,MAAgC,MAAM,mBAAmB,QAAQ,aAAY,6BAAe,MAAM,UAAU,MAAM,cAAc,GAAG,CAAC,MAAM,gBAAgB,MAAM,QAAQ,CAAC;AACnL,SAAO,oCAAC,+BAAS,OAAc,WAC1B,MAAM,QACT;AACJ;;;AbhDA,IAAM,YAA2B,qDAAe,yBAAW,GAAG,iBAAiB,CAAC;","names":["import_toolkit","import_react_redux","arg","options","promise","rrBatch","rrUseDispatch","rrUseSelector","rrUseStore","_createSelector","_formatProdErrorMessage","import_toolkit","_formatProdErrorMessage"]}
Index: node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.production.min.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+"use strict";var me=Object.create;var G=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var he=(e,s)=>{for(var f in s)G(e,f,{get:s[f],enumerable:!0})},$=(e,s,f,D)=>{if(s&&typeof s=="object"||typeof s=="function")for(let U of Be(s))!Ae.call(e,U)&&U!==f&&G(e,U,{get:()=>s[U],enumerable:!(D=Se(s,U))||D.enumerable});return e},O=(e,s,f)=>($(e,s,"default"),f&&$(f,s,"default")),Ie=(e,s,f)=>(f=e!=null?me(Pe(e)):{},$(s||!e||!e.__esModule?G(f,"default",{value:e,enumerable:!0}):f,e)),Ue=e=>$(G({},"__esModule",{value:!0}),e);var E={};he(E,{ApiProvider:()=>Re,UNINITIALIZED_VALUE:()=>K,createApi:()=>Ne,reactHooksModule:()=>ye,reactHooksModuleName:()=>ue});module.exports=Ue(E);var d=require("@reduxjs/toolkit/query");var yt=require("@reduxjs/toolkit"),M=require("react-redux"),le=require("reselect");function W(e){return e.replace(e[0],e[0].toUpperCase())}var be="query",Ee="mutation",ke="infinitequery";function fe(e){return e.type===be}function Qe(e){return e.type===Ee}function Z(e){return e.type===ke}function q(e,...s){return Object.assign(e,...s)}var J=require("@reduxjs/toolkit");var t=require("react");var m=require("react-redux");var K=Symbol();function Y(e){let s=(0,t.useRef)(e),f=(0,t.useMemo)(()=>(0,d.copyWithStructuralSharing)(s.current,e),[e]);return(0,t.useEffect)(()=>{s.current!==f&&(s.current=f)},[f]),f}function C(e){let s=(0,t.useRef)(e);return(0,t.useEffect)(()=>{(0,m.shallowEqual)(s.current,e)||(s.current=e)},[e]),(0,m.shallowEqual)(s.current,e)?s.current:e}var Oe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Me=Oe(),Fe=()=>typeof navigator<"u"&&navigator.product==="ReactNative",we=Fe(),ve=()=>Me||we?t.useLayoutEffect:t.useEffect,Ce=ve(),ce=e=>e.isUninitialized?{...e,isUninitialized:!1,isFetching:!0,isLoading:e.data===void 0,status:d.QueryStatus.pending}:e;function se(e,...s){let f={};return s.forEach(D=>{f[D]=e[D]}),f}var ae=["data","status","isLoading","isSuccess","isError","error"];function de({api:e,moduleOptions:{batch:s,hooks:{useDispatch:f,useSelector:D,useStore:U},unstable__sideEffectsInRender:b,createSelector:N},serializeQueryArgs:k,context:L}){let F=b?n=>n():t.useEffect,H=n=>n.current?.unsubscribe?.(),V=L.endpointDefinitions;return{buildQueryHooks:re,buildInfiniteQueryHooks:ge,buildMutationHook:Te,usePrefetch:_};function te(n,a,c){if(a?.endpointName&&n.isUninitialized){let{endpointName:y}=a,p=V[y];c!==d.skipToken&&k({queryArgs:a.originalArgs,endpointDefinition:p,endpointName:y})===k({queryArgs:c,endpointDefinition:p,endpointName:y})&&(a=void 0)}let o=n.isSuccess?n.data:a?.data;o===void 0&&(o=n.data);let u=o!==void 0,r=n.isLoading,i=(!a||a.isLoading||a.isUninitialized)&&!u&&r,Q=n.isSuccess||u&&(r&&!a?.isError||n.isUninitialized);return{...n,data:o,currentData:n.data,isFetching:r,isLoading:i,isSuccess:Q}}function B(n,a,c){if(a?.endpointName&&n.isUninitialized){let{endpointName:y}=a,p=V[y];c!==d.skipToken&&k({queryArgs:a.originalArgs,endpointDefinition:p,endpointName:y})===k({queryArgs:c,endpointDefinition:p,endpointName:y})&&(a=void 0)}let o=n.isSuccess?n.data:a?.data;o===void 0&&(o=n.data);let u=o!==void 0,r=n.isLoading,i=(!a||a.isLoading||a.isUninitialized)&&!u&&r,Q=n.isSuccess||r&&u;return{...n,data:o,currentData:n.data,isFetching:r,isLoading:i,isSuccess:Q}}function _(n,a){let c=f(),o=C(a);return(0,t.useCallback)((u,r)=>c(e.util.prefetch(n,u,{...o,...r})),[n,c,o])}function I(n,a,{refetchOnReconnect:c,refetchOnFocus:o,refetchOnMountOrArgChange:u,skip:r=!1,pollingInterval:i=0,skipPollingIfUnfocused:Q=!1,...y}={}){let{initiate:p}=e.endpoints[n],g=f(),P=(0,t.useRef)(void 0);if(!P.current){let v=g(e.internalActions.internal_getRTKQSubscriptions());P.current=v}let l=Y(r?d.skipToken:a),R=C({refetchOnReconnect:c,refetchOnFocus:o,pollingInterval:i,skipPollingIfUnfocused:Q}),x=y.initialPageParam,T=C(x),A=y.refetchCachedPages,h=C(A),S=(0,t.useRef)(void 0),{queryCacheKey:j,requestId:oe}=S.current||{},pe=!1;j&&oe&&(pe=P.current.isRequestSubscribed(j,oe));let ie=!pe&&S.current!==void 0;return F(()=>{ie&&(S.current=void 0)},[ie]),F(()=>{let v=S.current;if(typeof process<"u",l===d.skipToken){v?.unsubscribe(),S.current=void 0;return}let De=S.current?.subscriptionOptions;if(!v||v.arg!==l){v?.unsubscribe();let xe=g(p(l,{subscriptionOptions:R,forceRefetch:u,...Z(V[n])?{initialPageParam:T,refetchCachedPages:h}:{}}));S.current=xe}else R!==De&&v.updateSubscriptionOptions(R)},[g,p,u,l,R,ie,T,h,n]),[S,g,p,R]}function w(n,a){return(o,{skip:u=!1,selectFromResult:r}={})=>{let{select:i}=e.endpoints[n],Q=Y(u?d.skipToken:o),y=(0,t.useRef)(void 0),p=(0,t.useMemo)(()=>N([i(Q),(x,T)=>T,x=>Q],a,{memoizeOptions:{resultEqualityCheck:m.shallowEqual}}),[i,Q]),g=(0,t.useMemo)(()=>r?N([p],r,{devModeChecks:{identityFunctionCheck:"never"}}):p,[p,r]),P=D(x=>g(x,y.current),m.shallowEqual),l=U(),R=p(l.getState(),y.current);return Ce(()=>{y.current=R},[R]),P}}function z(n){(0,t.useEffect)(()=>()=>{H(n),n.current=void 0},[n])}function ne(n){if(!n.current)throw new Error((0,J.formatProdErrorMessage)(38));return n.current.refetch()}function re(n){let a=(u,r={})=>{let[i]=I(n,u,r);return z(i),(0,t.useMemo)(()=>({refetch:()=>ne(i)}),[i])},c=({refetchOnReconnect:u,refetchOnFocus:r,pollingInterval:i=0,skipPollingIfUnfocused:Q=!1}={})=>{let{initiate:y}=e.endpoints[n],p=f(),[g,P]=(0,t.useState)(K),l=(0,t.useRef)(void 0),R=C({refetchOnReconnect:u,refetchOnFocus:r,pollingInterval:i,skipPollingIfUnfocused:Q});F(()=>{let h=l.current?.subscriptionOptions;R!==h&&l.current?.updateSubscriptionOptions(R)},[R]);let x=(0,t.useRef)(R);F(()=>{x.current=R},[R]);let T=(0,t.useCallback)(function(h,S=!1){let j;return s(()=>{H(l),l.current=j=p(y(h,{subscriptionOptions:x.current,forceRefetch:!S})),P(h)}),j},[p,y]),A=(0,t.useCallback)(()=>{l.current?.queryCacheKey&&p(e.internalActions.removeQueryResult({queryCacheKey:l.current?.queryCacheKey}))},[p]);return(0,t.useEffect)(()=>()=>{H(l)},[]),(0,t.useEffect)(()=>{g!==K&&!l.current&&T(g,!0)},[g,T]),(0,t.useMemo)(()=>[T,g,{reset:A}],[T,g,A])},o=w(n,te);return{useQueryState:o,useQuerySubscription:a,useLazyQuerySubscription:c,useLazyQuery(u){let[r,i,{reset:Q}]=c(u),y=o(i,{...u,skip:i===K}),p=(0,t.useMemo)(()=>({lastArg:i}),[i]);return(0,t.useMemo)(()=>[r,{...y,reset:Q},p],[r,y,Q,p])},useQuery(u,r){let i=a(u,r),Q=o(u,{selectFromResult:u===d.skipToken||r?.skip?void 0:ce,...r}),y=se(Q,...ae);return(0,t.useDebugValue)(y),(0,t.useMemo)(()=>({...Q,...i}),[Q,i])}}}function ge(n){let a=(o,u={})=>{let[r,i,Q,y]=I(n,o,u),p=(0,t.useRef)(y);F(()=>{p.current=y},[y]);let g=u.refetchCachedPages,P=C(g),l=(0,t.useCallback)(function(T,A){let h;return s(()=>{H(r),r.current=h=i(Q(T,{subscriptionOptions:p.current,direction:A}))}),h},[r,i,Q]);z(r);let R=Y(u.skip?d.skipToken:o),x=(0,t.useCallback)(T=>{if(!r.current)throw new Error((0,J.formatProdErrorMessage)(38));let A={refetchCachedPages:T?.refetchCachedPages??P};return r.current.refetch(A)},[r,P]);return(0,t.useMemo)(()=>({trigger:l,refetch:x,fetchNextPage:()=>l(R,"forward"),fetchPreviousPage:()=>l(R,"backward")}),[x,l,R])},c=w(n,B);return{useInfiniteQueryState:c,useInfiniteQuerySubscription:a,useInfiniteQuery(o,u){let{refetch:r,fetchNextPage:i,fetchPreviousPage:Q}=a(o,u),y=c(o,{selectFromResult:o===d.skipToken||u?.skip?void 0:ce,...u}),p=se(y,...ae,"hasNextPage","hasPreviousPage");return(0,t.useDebugValue)(p),(0,t.useMemo)(()=>({...y,fetchNextPage:i,fetchPreviousPage:Q,refetch:r}),[y,i,Q,r])}}}function Te(n){return({selectFromResult:a,fixedCacheKey:c}={})=>{let{select:o,initiate:u}=e.endpoints[n],r=f(),[i,Q]=(0,t.useState)();(0,t.useEffect)(()=>()=>{i?.arg.fixedCacheKey||i?.reset()},[i]);let y=(0,t.useCallback)(function(h){let S=r(u(h,{fixedCacheKey:c}));return Q(S),S},[r,u,c]),{requestId:p}=i||{},g=(0,t.useMemo)(()=>o({fixedCacheKey:c,requestId:i?.requestId}),[c,i,o]),P=(0,t.useMemo)(()=>a?N([g],a):g,[a,g]),l=D(P,m.shallowEqual),R=c==null?i?.arg.originalArgs:void 0,x=(0,t.useCallback)(()=>{s(()=>{i&&Q(void 0),c&&r(e.internalActions.removeMutationResult({requestId:p,fixedCacheKey:c}))})},[r,c,i,p]),T=se(l,...ae,"endpointName");(0,t.useDebugValue)(T);let A=(0,t.useMemo)(()=>({...l,originalArgs:R,reset:x}),[l,R,x]);return(0,t.useMemo)(()=>[y,A],[y,A])}}}var ue=Symbol(),ye=({batch:e=M.batch,hooks:s={useDispatch:M.useDispatch,useSelector:M.useSelector,useStore:M.useStore},createSelector:f=le.createSelector,unstable__sideEffectsInRender:D=!1,...U}={})=>({name:ue,init(b,{serializeQueryArgs:N},k){let L=b,{buildQueryHooks:F,buildInfiniteQueryHooks:H,buildMutationHook:V,usePrefetch:te}=de({api:b,moduleOptions:{batch:e,hooks:s,unstable__sideEffectsInRender:D,createSelector:f},serializeQueryArgs:N,context:k});return q(L,{usePrefetch:te}),q(k,{batch:e}),{injectEndpoint(B,_){if(fe(_)){let{useQuery:I,useLazyQuery:w,useLazyQuerySubscription:z,useQueryState:ne,useQuerySubscription:re}=F(B);q(L.endpoints[B],{useQuery:I,useLazyQuery:w,useLazyQuerySubscription:z,useQueryState:ne,useQuerySubscription:re}),b[`use${W(B)}Query`]=I,b[`useLazy${W(B)}Query`]=w}if(Qe(_)){let I=V(B);q(L.endpoints[B],{useMutation:I}),b[`use${W(B)}Mutation`]=I}else if(Z(_)){let{useInfiniteQuery:I,useInfiniteQuerySubscription:w,useInfiniteQueryState:z}=H(B);q(L.endpoints[B],{useInfiniteQuery:I,useInfiniteQuerySubscription:w,useInfiniteQueryState:z}),b[`use${W(B)}InfiniteQuery`]=I}}}}});O(E,require("@reduxjs/toolkit/query"),module.exports);var X=require("@reduxjs/toolkit");var ee=Ie(require("react"));function Re(e){let s=e.context||m.ReactReduxContext;if((0,t.useContext)(s))throw new Error((0,X.formatProdErrorMessage)(35));let[D]=ee.useState(()=>(0,X.configureStore)({reducer:{[e.api.reducerPath]:e.api.reducer},middleware:U=>U().concat(e.api.middleware)}));return(0,t.useEffect)(()=>e.setupListeners===!1?void 0:(0,d.setupListeners)(D.dispatch,e.setupListeners),[e.setupListeners,D.dispatch]),ee.createElement(m.Provider,{store:D,context:s},e.children)}var Ne=(0,d.buildCreateApi)((0,d.coreModule)(),ye());0&&(module.exports={ApiProvider,UNINITIALIZED_VALUE,createApi,reactHooksModule,reactHooksModuleName,...require("@reduxjs/toolkit/query")});
+//# sourceMappingURL=rtk-query-react.production.min.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.production.min.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/cjs/rtk-query-react.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../../src/query/react/index.ts","../../../../src/query/react/rtkqImports.ts","../../../../src/query/react/module.ts","../../../../src/query/utils/capitalize.ts","../../../../src/query/endpointDefinitions.ts","../../../../src/query/tsHelpers.ts","../../../../src/query/react/buildHooks.ts","../../../../src/query/react/reactImports.ts","../../../../src/query/react/reactReduxImports.ts","../../../../src/query/react/constants.ts","../../../../src/query/react/useSerializedStableValue.ts","../../../../src/query/react/useShallowStableValue.ts","../../../../src/query/react/ApiProvider.tsx"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nimport { buildCreateApi, coreModule } from './rtkqImports';\nimport { reactHooksModule, reactHooksModuleName } from './module';\nexport * from '@reduxjs/toolkit/query';\nexport { ApiProvider } from './ApiProvider';\nconst createApi = /* @__PURE__ */buildCreateApi(coreModule(), reactHooksModule());\nexport 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';\nexport { UNINITIALIZED_VALUE } from './constants';\nexport { createApi, reactHooksModule, reactHooksModuleName };","export { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from '@reduxjs/toolkit/query';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Api, BaseQueryFn, EndpointDefinitions, InfiniteQueryDefinition, Module, MutationDefinition, PrefetchOptions, QueryArgFrom, QueryDefinition, QueryKeys } from '@reduxjs/toolkit/query';\nimport { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from 'react-redux';\nimport type { CreateSelectorFunction } from 'reselect';\nimport { createSelector as _createSelector } from 'reselect';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { safeAssign } from '../tsHelpers';\nimport { capitalize, countObjectKeys } from '../utils';\nimport type { InfiniteQueryHooks, MutationHooks, QueryHooks } from './buildHooks';\nimport { buildHooks } from './buildHooks';\nimport type { HooksWithUniqueNames } from './namedHooks';\nexport const reactHooksModuleName = /* @__PURE__ */Symbol();\nexport type ReactHooksModule = typeof reactHooksModuleName;\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  ReducerPath extends string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  TagTypes extends string> {\n    [reactHooksModuleName]: {\n      /**\n       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n       */\n      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 };\n      /**\n       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n       */\n      usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;\n    } & HooksWithUniqueNames<Definitions>;\n  }\n}\ntype RR = typeof import('react-redux');\nexport interface ReactHooksModuleOptions {\n  /**\n   * The hooks from React Redux to be used\n   */\n  hooks?: {\n    /**\n     * The version of the `useDispatch` hook to be used\n     */\n    useDispatch: RR['useDispatch'];\n    /**\n     * The version of the `useSelector` hook to be used\n     */\n    useSelector: RR['useSelector'];\n    /**\n     * The version of the `useStore` hook to be used\n     */\n    useStore: RR['useStore'];\n  };\n  /**\n   * The version of the `batchedUpdates` function to be used\n   */\n  batch?: RR['batch'];\n  /**\n   * Enables performing asynchronous tasks immediately within a render.\n   *\n   * @example\n   *\n   * ```ts\n   * import {\n   *   buildCreateApi,\n   *   coreModule,\n   *   reactHooksModule\n   * } from '@reduxjs/toolkit/query/react'\n   *\n   * const createApi = buildCreateApi(\n   *   coreModule(),\n   *   reactHooksModule({ unstable__sideEffectsInRender: true })\n   * )\n   * ```\n   */\n  unstable__sideEffectsInRender?: boolean;\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n *  @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n  batch = rrBatch,\n  hooks = {\n    useDispatch: rrUseDispatch,\n    useSelector: rrUseSelector,\n    useStore: rrUseStore\n  },\n  createSelector = _createSelector,\n  unstable__sideEffectsInRender = false,\n  ...rest\n}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {\n  if (process.env.NODE_ENV !== 'production') {\n    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const;\n    let warned = false;\n    for (const hookName of hookNames) {\n      // warn for old hook options\n      if (countObjectKeys(rest) > 0) {\n        if ((rest as Partial<typeof hooks>)[hookName]) {\n          if (!warned) {\n            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 } })`');\n            warned = true;\n          }\n        }\n        // migrate\n        // @ts-ignore\n        hooks[hookName] = rest[hookName];\n      }\n      // then make sure we have them all\n      if (typeof hooks[hookName] !== 'function') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(36) : `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.`);\n      }\n    }\n  }\n  return {\n    name: reactHooksModuleName,\n    init(api, {\n      serializeQueryArgs\n    }, context) {\n      const anyApi = api as any as Api<any, Record<string, any>, any, any, ReactHooksModule>;\n      const {\n        buildQueryHooks,\n        buildInfiniteQueryHooks,\n        buildMutationHook,\n        usePrefetch\n      } = buildHooks({\n        api,\n        moduleOptions: {\n          batch,\n          hooks,\n          unstable__sideEffectsInRender,\n          createSelector\n        },\n        serializeQueryArgs,\n        context\n      });\n      safeAssign(anyApi, {\n        usePrefetch\n      });\n      safeAssign(context, {\n        batch\n      });\n      return {\n        injectEndpoint(endpointName, definition) {\n          if (isQueryDefinition(definition)) {\n            const {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            } = buildQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            });\n            (api as any)[`use${capitalize(endpointName)}Query`] = useQuery;\n            (api as any)[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;\n          }\n          if (isMutationDefinition(definition)) {\n            const useMutation = buildMutationHook(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useMutation\n            });\n            (api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation;\n          } else if (isInfiniteQueryDefinition(definition)) {\n            const {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            } = buildInfiniteQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            });\n            (api as any)[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;\n          }\n        }\n      };\n    }\n  };\n};","export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase());\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Selector, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport 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';\nimport { QueryStatus, skipToken } from './rtkqImports';\nimport type { DependencyList } from 'react';\nimport { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/index';\nimport type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index';\nimport type { UninitializedValue } from './constants';\nimport { UNINITIALIZED_VALUE } from './constants';\nimport type { ReactHooksModuleOptions } from './module';\nimport { useStableQueryArgs } from './useSerializedStableValue';\nimport { useShallowStableValue } from './useShallowStableValue';\nimport type { InfiniteQueryDirection } from '../core/apiState';\nimport { isInfiniteQueryDefinition } from '../endpointDefinitions';\nimport type { StartInfiniteQueryActionCreator } from '../core/buildInitiate';\n\n// Copy-pasted from React-Redux\nconst canUseDOM = () => !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nconst isDOM = /* @__PURE__ */canUseDOM();\n\n// Under React Native, we know that we always want to use useLayoutEffect\n\nconst isRunningInReactNative = () => typeof navigator !== 'undefined' && navigator.product === 'ReactNative';\nconst isReactNative = /* @__PURE__ */isRunningInReactNative();\nconst getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;\nexport const useIsomorphicLayoutEffect = /* @__PURE__ */getUseIsomorphicLayoutEffect();\nexport type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  useQuery: UseQuery<Definition>;\n  useLazyQuery: UseLazyQuery<Definition>;\n  useQuerySubscription: UseQuerySubscription<Definition>;\n  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;\n  useQueryState: UseQueryState<Definition>;\n};\nexport type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  useInfiniteQuery: UseInfiniteQuery<Definition>;\n  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;\n  useInfiniteQueryState: UseInfiniteQueryState<Definition>;\n};\nexport type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  useMutation: UseMutation<Definition>;\n};\n\n/**\n * 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.\n *\n * 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.\n *\n * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuery` hook in userland code.\n */\nexport type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;\nexport type UseQuerySubscriptionOptions = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n};\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;\nexport type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {\n  lastArg: QueryArgFrom<D>;\n};\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - 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\n *\n * #### Note\n *\n * 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.\n */\nexport 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>];\nexport type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useLazyQuery` hook in userland code.\n */\nexport type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\nexport type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;\n};\nexport type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - 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\n */\nexport type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, {\n  reset: () => void;\n}];\nexport type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   title: string\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * type SelectedResult = Pick<PostsApiResponse, 'posts'>\n *\n * const postsApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, QueryArgument>({\n *       query: (limit = 5) => `?limit=${limit}&select=title`,\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = postsApiSlice\n *\n * function PostById({ id }: { id: number }) {\n *   const { post } = useGetPostsQuery(undefined, {\n *     selectFromResult: (state) => ({\n *       post: state.data?.posts.find((post) => post.id === id),\n *     }),\n *   })\n *\n *   return <li>{post?.title}</li>\n * }\n *\n * const EMPTY_ARRAY: Post[] = []\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n *\n * function PostsList() {\n *   const { posts } = useGetPostsQuery(undefined, {\n *     selectFromResult: typedSelectFromResult,\n *   })\n *\n *   return (\n *     <div>\n *       <ul>\n *         {posts.map((post) => (\n *           <PostById key={post.id} id={post.id} />\n *         ))}\n *       </ul>\n *     </div>\n *   )\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.3.0\n * @public\n */\nexport 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>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: QueryStateSelector<R, D>;\n};\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * <caption>#### __Create a `useQuery` hook with default options__</caption>\n *\n * ```ts\n * import type {\n *   SubscriptionOptions,\n *   TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   name: string\n * }\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   tagTypes: ['Post'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<Post[], void>({\n *       query: () => 'posts',\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = api\n *\n * export const useGetPostsQueryWithDefaults = <\n *   SelectedResult extends Record<string, any>,\n * >(\n *   overrideOptions: TypedUseQueryStateOptions<\n *     Post[],\n *     void,\n *     ReturnType<typeof fetchBaseQuery>,\n *     SelectedResult\n *   > &\n *     SubscriptionOptions,\n * ) =>\n *   useGetPostsQuery(undefined, {\n *     // Insert default options here\n *\n *     refetchOnMountOrArgChange: true,\n *     refetchOnFocus: true,\n *     ...overrideOptions,\n *   })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.2.8\n * @public\n */\nexport 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>;\nexport type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;\ntype UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: ResultTypeFrom<D>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n};\ntype UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}>;\ntype UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n}>;\ntype UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n  currentData: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isError: true;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;\ntype UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;\n};\nexport type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  initialPageParam?: PageParamFrom<D>;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   *\n   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).\n   * It can be overridden on a per-call basis using the `refetch()` method.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  refetch: (options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>) => InfiniteQueryActionCreatorResult<D>;\n  trigger: LazyInfiniteQueryTrigger<D>;\n  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;\nexport 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>>;\n\n/**\n * 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.\n *\n * 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.\n *\n *  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.\n *\n * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.\n *\n * 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.\n *\n * 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.\n *\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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'>;\nexport type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;\nexport type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;\nexport 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>;\nexport type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: InfiniteQueryStateSelector<R, D>;\n};\nexport 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>;\nexport type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;\nexport 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>;\ntype UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n};\ntype UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n} | ({\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({\n  isError: true;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;\nexport type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  selectFromResult?: MutationStateSelector<R, D>;\n  fixedCacheKey?: string;\n};\nexport type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {\n  originalArgs?: QueryArgFrom<D>;\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\n\n/**\n * 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.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>];\nexport type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {\n  /**\n   * Triggers the mutation and returns a Promise.\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;\n};\nexport type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector<any, any> = selected => {\n  if (selected.isUninitialized) {\n    return {\n      ...selected,\n      isUninitialized: false,\n      isFetching: true,\n      isLoading: selected.data !== undefined ? false : true,\n      // This is the one place where we still have to use `QueryStatus` as an enum,\n      // since it's the only reference in the React package and not in the core.\n      status: QueryStatus.pending\n    } as any;\n  }\n  return selected;\n};\nfunction pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {\n  const ret: any = {};\n  keys.forEach(key => {\n    ret[key] = obj[key];\n  });\n  return ret;\n}\nconst COMMON_HOOK_DEBUG_FIELDS = ['data', 'status', 'isLoading', 'isSuccess', 'isError', 'error'] as const;\ntype GenericPrefetchThunk = (endpointName: any, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, UnknownAction>;\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks<Definitions extends EndpointDefinitions>({\n  api,\n  moduleOptions: {\n    batch,\n    hooks: {\n      useDispatch,\n      useSelector,\n      useStore\n    },\n    unstable__sideEffectsInRender,\n    createSelector\n  },\n  serializeQueryArgs,\n  context\n}: {\n  api: Api<any, Definitions, any, any, CoreModule>;\n  moduleOptions: Required<ReactHooksModuleOptions>;\n  serializeQueryArgs: SerializeQueryArgs<any>;\n  context: ApiContext<Definitions>;\n}) {\n  const usePossiblyImmediateEffect: (effect: () => void | undefined, deps?: DependencyList) => void = unstable__sideEffectsInRender ? cb => cb() : useEffect;\n  type UnsubscribePromiseRef = React.RefObject<{\n    unsubscribe?: () => void;\n  } | undefined>;\n  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) => ref.current?.unsubscribe?.();\n  const endpointDefinitions = context.endpointDefinitions;\n  return {\n    buildQueryHooks,\n    buildInfiniteQueryHooks,\n    buildMutationHook,\n    usePrefetch\n  };\n  function queryStatePreSelector(currentState: QueryResultSelectorResult<any>, lastResult: UseQueryStateDefaultResult<any> | undefined, queryArgs: any): UseQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n\n    // isSuccess = true when data is present and we're not refetching after an error.\n    // That includes cases where the _current_ item is either actively\n    // fetching or about to fetch due to an uninitialized entry.\n    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseQueryStateDefaultResult<any>;\n  }\n  function infiniteQueryStatePreSelector(currentState: InfiniteQueryResultSelectorResult<any>, lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined, queryArgs: any): UseInfiniteQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n    // isSuccess = true when data is present\n    const isSuccess = currentState.isSuccess || isFetching && hasData;\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseInfiniteQueryStateDefaultResult<any>;\n  }\n  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions) {\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n    const stableDefaultOptions = useShallowStableValue(defaultOptions);\n    return useCallback((arg: any, options?: PrefetchOptions) => dispatch((api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n      ...stableDefaultOptions,\n      ...options\n    })), [endpointName, dispatch, stableDefaultOptions]);\n  }\n  function useQuerySubscriptionCommonImpl<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(endpointName: string, arg: unknown | SkipToken, {\n    refetchOnReconnect,\n    refetchOnFocus,\n    refetchOnMountOrArgChange,\n    skip = false,\n    pollingInterval = 0,\n    skipPollingIfUnfocused = false,\n    ...rest\n  }: UseQuerySubscriptionOptions = {}) {\n    const {\n      initiate\n    } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n\n    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.\n    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(undefined);\n    if (!subscriptionSelectorsRef.current) {\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n    You must add the middleware for RTK-Query to function correctly!`);\n        }\n      }\n      subscriptionSelectorsRef.current = returnedValue as unknown as SubscriptionSelectors;\n    }\n    const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n    const stableSubscriptionOptions = useShallowStableValue({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval,\n      skipPollingIfUnfocused\n    });\n    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>).initialPageParam;\n    const stableInitialPageParam = useShallowStableValue(initialPageParam);\n    const refetchCachedPages = (rest as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);\n\n    /**\n     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n     */\n    const promiseRef = useRef<T | undefined>(undefined);\n    let {\n      queryCacheKey,\n      requestId\n    } = promiseRef.current || {};\n\n    // HACK We've saved the middleware subscription lookup callbacks into a ref,\n    // so we can directly check here if the subscription exists for this query.\n    let currentRenderHasSubscription = false;\n    if (queryCacheKey && requestId) {\n      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);\n    }\n    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== undefined;\n    usePossiblyImmediateEffect((): void | undefined => {\n      if (subscriptionRemoved) {\n        promiseRef.current = undefined;\n      }\n    }, [subscriptionRemoved]);\n    usePossiblyImmediateEffect((): void | undefined => {\n      const lastPromise = promiseRef.current;\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {\n        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n        console.log(subscriptionRemoved);\n      }\n      if (stableArg === skipToken) {\n        lastPromise?.unsubscribe();\n        promiseRef.current = undefined;\n        return;\n      }\n      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n      if (!lastPromise || lastPromise.arg !== stableArg) {\n        lastPromise?.unsubscribe();\n        const promise = dispatch(initiate(stableArg, {\n          subscriptionOptions: stableSubscriptionOptions,\n          forceRefetch: refetchOnMountOrArgChange,\n          ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {\n            initialPageParam: stableInitialPageParam,\n            refetchCachedPages: stableRefetchCachedPages\n          } : {})\n        }));\n        promiseRef.current = promise as T;\n      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\n      }\n    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);\n    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const;\n  }\n  function buildUseQueryState(endpointName: string, preSelector: typeof queryStatePreSelector | typeof infiniteQueryStatePreSelector) {\n    const useQueryState = (arg: any, {\n      skip = false,\n      selectFromResult\n    }: UseQueryStateOptions<any, any> | UseInfiniteQueryStateOptions<any, any> = {}) => {\n      const {\n        select\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n      type ApiRootState = Parameters<ReturnType<typeof select>>[0];\n      const lastValue = useRef<any>(undefined);\n      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(() =>\n      // Normally ts-ignores are bad and should be avoided, but we're\n      // already casting this selector to be `Selector<any>` anyway,\n      // so the inconsistencies don't matter here\n      // @ts-ignore\n      createSelector([\n      // @ts-ignore\n      select(stableArg), (_: ApiRootState, lastResult: any) => lastResult, (_: ApiRootState) => stableArg], preSelector, {\n        memoizeOptions: {\n          resultEqualityCheck: shallowEqual\n        }\n      }), [select, stableArg]);\n      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {\n        devModeChecks: {\n          identityFunctionCheck: 'never'\n        }\n      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);\n      const currentState = useSelector((state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current), shallowEqual);\n      const store = useStore<RootState<Definitions, any, any>>();\n      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);\n      useIsomorphicLayoutEffect(() => {\n        lastValue.current = newLastValue;\n      }, [newLastValue]);\n      return currentState;\n    };\n    return useQueryState;\n  }\n  function usePromiseRefUnsubscribeOnUnmount(promiseRef: UnsubscribePromiseRef) {\n    useEffect(() => {\n      return () => {\n        unsubscribePromiseRef(promiseRef)\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        ;\n        (promiseRef.current as any) = undefined;\n      };\n    }, [promiseRef]);\n  }\n  function refetchOrErrorIfUnmounted<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(promiseRef: React.RefObject<T | undefined>): T {\n    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(38) : 'Cannot refetch a query that has not been started yet.');\n    return promiseRef.current.refetch() as T;\n  }\n  function buildQueryHooks(endpointName: string): QueryHooks<any> {\n    const useQuerySubscription: UseQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef] = useQuerySubscriptionCommonImpl<QueryActionCreatorResult<any>>(endpointName, arg, options);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      return useMemo(() => ({\n        /**\n         * A method to manually refetch data for the query\n         */\n        refetch: () => refetchOrErrorIfUnmounted(promiseRef)\n      }), [promiseRef]);\n    };\n    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false\n    } = {}) => {\n      const {\n        initiate\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE);\n\n      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n      /**\n       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n       */\n      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(undefined);\n      const stableSubscriptionOptions = useShallowStableValue({\n        refetchOnReconnect,\n        refetchOnFocus,\n        pollingInterval,\n        skipPollingIfUnfocused\n      });\n      usePossiblyImmediateEffect(() => {\n        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n        if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n          promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);\n        }\n      }, [stableSubscriptionOptions]);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n      const trigger = useCallback(function (arg: any, preferCacheValue = false) {\n        let promise: QueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch(initiate(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            forceRefetch: !preferCacheValue\n          }));\n          setArg(arg);\n        });\n        return promise!;\n      }, [dispatch, initiate]);\n      const reset = useCallback(() => {\n        if (promiseRef.current?.queryCacheKey) {\n          dispatch(api.internalActions.removeQueryResult({\n            queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey\n          }));\n        }\n      }, [dispatch]);\n\n      /* cleanup on unmount */\n      useEffect(() => {\n        return () => {\n          unsubscribePromiseRef(promiseRef);\n        };\n      }, []);\n\n      /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n      useEffect(() => {\n        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n          trigger(arg, true);\n        }\n      }, [arg, trigger]);\n      return useMemo(() => [trigger, arg, {\n        reset\n      }] as const, [trigger, arg, reset]);\n    };\n    const useQueryState: UseQueryState<any> = buildUseQueryState(endpointName, queryStatePreSelector);\n    return {\n      useQueryState,\n      useQuerySubscription,\n      useLazyQuerySubscription,\n      useLazyQuery(options) {\n        const [trigger, arg, {\n          reset\n        }] = useLazyQuerySubscription(options);\n        const queryStateResults = useQueryState(arg, {\n          ...options,\n          skip: arg === UNINITIALIZED_VALUE\n        });\n        const info = useMemo(() => ({\n          lastArg: arg\n        }), [arg]);\n        return useMemo(() => [trigger, {\n          ...queryStateResults,\n          reset\n        }, info], [trigger, queryStateResults, reset, info]);\n      },\n      useQuery(arg, options) {\n        const querySubscriptionResults = useQuerySubscription(arg, options);\n        const queryStateResults = useQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          ...querySubscriptionResults\n        }), [queryStateResults, querySubscriptionResults]);\n      }\n    };\n  }\n  function buildInfiniteQueryHooks(endpointName: string): InfiniteQueryHooks<any> {\n    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(endpointName, arg, options);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n\n      // Extract and stabilize the hook-level refetchCachedPages option\n      const hookRefetchCachedPages = (options as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);\n      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(function (arg: unknown, direction: 'forward' | 'backward') {\n        let promise: InfiniteQueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch((initiate as StartInfiniteQueryActionCreator<any>)(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            direction\n          }));\n        });\n        return promise!;\n      }, [promiseRef, dispatch, initiate]);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);\n      const refetch = useCallback((options?: Pick<UseInfiniteQuerySubscriptionOptions<any>, 'refetchCachedPages'>) => {\n        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(38) : 'Cannot refetch a query that has not been started yet.');\n        // Merge per-call options with hook-level default\n        const mergedOptions = {\n          refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages\n        };\n        return promiseRef.current.refetch(mergedOptions);\n      }, [promiseRef, stableHookRefetchCachedPages]);\n      return useMemo(() => {\n        const fetchNextPage = () => {\n          return trigger(stableArg, 'forward');\n        };\n        const fetchPreviousPage = () => {\n          return trigger(stableArg, 'backward');\n        };\n        return {\n          trigger,\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        };\n      }, [refetch, trigger, stableArg]);\n    };\n    const useInfiniteQueryState: UseInfiniteQueryState<any> = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);\n    return {\n      useInfiniteQueryState,\n      useInfiniteQuerySubscription,\n      useInfiniteQuery(arg, options) {\n        const {\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        } = useInfiniteQuerySubscription(arg, options);\n        const queryStateResults = useInfiniteQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, 'hasNextPage', 'hasPreviousPage');\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          fetchNextPage,\n          fetchPreviousPage,\n          refetch\n        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);\n      }\n    };\n  }\n  function buildMutationHook(name: string): UseMutation<any> {\n    return ({\n      selectFromResult,\n      fixedCacheKey\n    } = {}) => {\n      const {\n        select,\n        initiate\n      } = api.endpoints[name] as ApiEndpointMutation<MutationDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>();\n      useEffect(() => () => {\n        if (!promise?.arg.fixedCacheKey) {\n          promise?.reset();\n        }\n      }, [promise]);\n      const triggerMutation = useCallback(function (arg: Parameters<typeof initiate>['0']) {\n        const promise = dispatch(initiate(arg, {\n          fixedCacheKey\n        }));\n        setPromise(promise);\n        return promise;\n      }, [dispatch, initiate, fixedCacheKey]);\n      const {\n        requestId\n      } = promise || {};\n      const selectDefaultResult = useMemo(() => select({\n        fixedCacheKey,\n        requestId: promise?.requestId\n      }), [fixedCacheKey, promise, select]);\n      const mutationSelector = useMemo((): Selector<RootState<Definitions, any, any>, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);\n      const currentState = useSelector(mutationSelector, shallowEqual);\n      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;\n      const reset = useCallback(() => {\n        batch(() => {\n          if (promise) {\n            setPromise(undefined);\n          }\n          if (fixedCacheKey) {\n            dispatch(api.internalActions.removeMutationResult({\n              requestId,\n              fixedCacheKey\n            }));\n          }\n        });\n      }, [dispatch, fixedCacheKey, promise, requestId]);\n      const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, 'endpointName');\n      useDebugValue(debugValue);\n      const finalState = useMemo(() => ({\n        ...currentState,\n        originalArgs,\n        reset\n      }), [currentState, originalArgs, reset]);\n      return useMemo(() => [triggerMutation, finalState] as const, [triggerMutation, finalState]);\n    };\n  }\n}","export { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from 'react';","export { shallowEqual, Provider, ReactReduxContext } from 'react-redux';","export const UNINITIALIZED_VALUE = Symbol();\nexport type UninitializedValue = typeof UNINITIALIZED_VALUE;","import { useEffect, useRef, useMemo } from './reactImports';\nimport { copyWithStructuralSharing } from './rtkqImports';\nexport function useStableQueryArgs<T>(queryArgs: T) {\n  const cache = useRef(queryArgs);\n  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);\n  useEffect(() => {\n    if (cache.current !== copy) {\n      cache.current = copy;\n    }\n  }, [copy]);\n  return copy;\n}","import { useEffect, useRef } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nexport function useShallowStableValue<T>(value: T) {\n  const cache = useRef(value);\n  useEffect(() => {\n    if (!shallowEqual(cache.current, value)) {\n      cache.current = value;\n    }\n  }, [value]);\n  return shallowEqual(cache.current, value) ? cache.current : value;\n}","import { configureStore, formatProdErrorMessage as _formatProdErrorMessage } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport { useContext, useEffect } from './reactImports';\nimport * as React from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { Provider, ReactReduxContext } from './reactReduxImports';\nimport { setupListeners } from './rtkqImports';\nimport type { Api } from '@reduxjs/toolkit/query';\n\n/**\n * Can be used as a `Provider` if you **do not already have a Redux store**.\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Basic usage - wrap your App with ApiProvider\"\n * import * as React from 'react';\n * import { ApiProvider } from '@reduxjs/toolkit/query/react';\n * import { Pokemon } from './features/Pokemon';\n *\n * function App() {\n *   return (\n *     <ApiProvider api={api}>\n *       <Pokemon />\n *     </ApiProvider>\n *   );\n * }\n * ```\n *\n * @remarks\n * Using this together with an existing redux store, both will\n * conflict with each other - please use the traditional redux setup\n * in that case.\n */\nexport function ApiProvider(props: {\n  children: any;\n  api: Api<any, {}, any, any>;\n  setupListeners?: Parameters<typeof setupListeners>[1] | false;\n  context?: Context<ReactReduxContextValue | null>;\n}) {\n  const context = props.context || ReactReduxContext;\n  const existingContext = useContext(context);\n  if (existingContext) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(35) : 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.');\n  }\n  const [store] = React.useState(() => configureStore({\n    reducer: {\n      [props.api.reducerPath]: props.api.reducer\n    },\n    middleware: gDM => gDM().concat(props.api.middleware)\n  }));\n  // Adds the event listeners for online/offline/focus/etc\n  useEffect((): undefined | (() => void) => props.setupListeners === false ? undefined : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);\n  return <Provider store={store} context={context}>\n      {props.children}\n    </Provider>;\n}"],"mappings":"qnBAAA,IAAAA,EAAA,GAAAC,GAAAD,EAAA,iBAAAE,GAAA,wBAAAC,EAAA,cAAAC,GAAA,qBAAAC,GAAA,yBAAAC,KAAA,eAAAC,GAAAP,GCAA,IAAAQ,EAA8G,kCCA9G,IAAAC,GAAkE,4BAElEC,EAAqH,uBAErHC,GAAkD,oBCJ3C,SAASC,EAAWC,EAAa,CACtC,OAAOA,EAAI,QAAQA,EAAI,CAAC,EAAGA,EAAI,CAAC,EAAE,YAAY,CAAC,CACjD,CCuYO,IAAMC,GAAiB,QACjBC,GAAoB,WACpBC,GAAyB,gBA+c/B,SAASC,GAAkB,EAA8G,CAC9I,OAAO,EAAE,OAASH,EACpB,CACO,SAASI,GAAqB,EAAiH,CACpJ,OAAO,EAAE,OAASH,EACpB,CACO,SAASI,EAA0B,EAA2H,CACnK,OAAO,EAAE,OAASH,EACpB,CC91BO,SAASI,EAA6BC,KAAcC,EAAqC,CAC9F,OAAO,OAAO,OAAOD,EAAQ,GAAGC,CAAI,CACtC,CCNA,IAAAC,EAA0K,4BCA1K,IAAAC,EAA8G,iBCA9G,IAAAC,EAA0D,uBCAnD,IAAMC,EAAsB,OAAO,ECEnC,SAASC,EAAsBC,EAAc,CAClD,IAAMC,KAAQ,UAAOD,CAAS,EACxBE,KAAO,WAAQ,OAAM,6BAA0BD,EAAM,QAASD,CAAS,EAAG,CAACA,CAAS,CAAC,EAC3F,sBAAU,IAAM,CACVC,EAAM,UAAYC,IACpBD,EAAM,QAAU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WN,EAAO,UAAUO,CAAY,EAAG,CACzC,YAAAU,CACF,CAAC,EACApB,EAAY,MAAMkB,EAAWR,CAAY,CAAC,UAAU,EAAIU,CAC3D,SAAWC,EAA0BV,CAAU,EAAG,CAChD,GAAM,CACJ,iBAAAW,EACA,6BAAAC,EACA,sBAAAC,CACF,EAAInB,EAAwBK,CAAY,EACxCD,EAAWN,EAAO,UAAUO,CAAY,EAAG,CACzC,iBAAAY,EACA,6BAAAC,EACA,sBAAAC,CACF,CAAC,EACAxB,EAAY,MAAMkB,EAAWR,CAAY,CAAC,eAAe,EAAIY,CAChE,CACF,CACF,CACF,CACF,GFvMFG,EAAAC,EAAc,kCALd,gBYAA,IAAAC,EAAkF,4BAGlF,IAAAC,GAAuB,qBA8BhB,SAASC,GAAYC,EAKzB,CACD,IAAMC,EAAUD,EAAM,SAAW,oBAEjC,MADwB,cAAWC,CAAO,EAExC,MAAM,IAAI,SAA8C,EAAAC,wBAAwB,EAAE,CAAkH,EAEtM,GAAM,CAACC,CAAK,EAAU,YAAS,OAAM,kBAAe,CAClD,QAAS,CACP,CAACH,EAAM,IAAI,WAAW,EAAGA,EAAM,IAAI,OACrC,EACA,WAAYI,GAAOA,EAAI,EAAE,OAAOJ,EAAM,IAAI,UAAU,CACtD,CAAC,CAAC,EAEF,sBAAU,IAAgCA,EAAM,iBAAmB,GAAQ,UAAY,kBAAeG,EAAM,SAAUH,EAAM,cAAc,EAAG,CAACA,EAAM,eAAgBG,EAAM,QAAQ,CAAC,EAC5K,iBAAC,YAAS,MAAOA,EAAO,QAASF,GACnCD,EAAM,QACT,CACJ,CZhDA,IAAMK,MAA2B,qBAAe,cAAW,EAAGC,GAAiB,CAAC","names":["react_exports","__export","ApiProvider","UNINITIALIZED_VALUE","createApi","reactHooksModule","reactHooksModuleName","__toCommonJS","import_query","import_toolkit","import_react_redux","import_reselect","capitalize","str","ENDPOINT_QUERY","ENDPOINT_MUTATION","ENDPOINT_INFINITEQUERY","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","safeAssign","target","args","import_toolkit","import_react","import_react_redux","UNINITIALIZED_VALUE","useStableQueryArgs","queryArgs","cache","copy","useShallowStableValue","value","cache","canUseDOM","isDOM","isRunningInReactNative","isReactNative","getUseIsomorphicLayoutEffect","useIsomorphicLayoutEffect","noPendingQueryStateSelector","selected","pick","obj","keys","ret","key","COMMON_HOOK_DEBUG_FIELDS","buildHooks","api","batch","useDispatch","useSelector","useStore","unstable__sideEffectsInRender","createSelector","serializeQueryArgs","context","usePossiblyImmediateEffect","cb","unsubscribePromiseRef","ref","endpointDefinitions","buildQueryHooks","buildInfiniteQueryHooks","buildMutationHook","usePrefetch","queryStatePreSelector","currentState","lastResult","queryArgs","endpointName","endpointDefinition","data","hasData","isFetching","isLoading","isSuccess","infiniteQueryStatePreSelector","defaultOptions","dispatch","stableDefaultOptions","useShallowStableValue","arg","options","useQuerySubscriptionCommonImpl","refetchOnReconnect","refetchOnFocus","refetchOnMountOrArgChange","skip","pollingInterval","skipPollingIfUnfocused","rest","initiate","subscriptionSelectorsRef","returnedValue","stableArg","useStableQueryArgs","stableSubscriptionOptions","initialPageParam","stableInitialPageParam","refetchCachedPages","stableRefetchCachedPages","promiseRef","queryCacheKey","requestId","currentRenderHasSubscription","subscriptionRemoved","lastPromise","lastSubscriptionOptions","promise","isInfiniteQueryDefinition","buildUseQueryState","preSelector","selectFromResult","select","lastValue","selectDefaultResult","_","querySelector","state","store","newLastValue","usePromiseRefUnsubscribeOnUnmount","refetchOrErrorIfUnmounted","_formatProdErrorMessage2","useQuerySubscription","useLazyQuerySubscription","setArg","UNINITIALIZED_VALUE","subscriptionOptionsRef","trigger","preferCacheValue","reset","useQueryState","queryStateResults","info","querySubscriptionResults","debugValue","useInfiniteQuerySubscription","hookRefetchCachedPages","stableHookRefetchCachedPages","direction","refetch","_formatProdErrorMessage3","mergedOptions","useInfiniteQueryState","fetchNextPage","fetchPreviousPage","name","fixedCacheKey","setPromise","triggerMutation","mutationSelector","originalArgs","finalState","reactHooksModuleName","reactHooksModule","batch","rrBatch","hooks","rrUseDispatch","rrUseSelector","rrUseStore","createSelector","_createSelector","unstable__sideEffectsInRender","rest","api","serializeQueryArgs","context","anyApi","buildQueryHooks","buildInfiniteQueryHooks","buildMutationHook","usePrefetch","buildHooks","safeAssign","endpointName","definition","isQueryDefinition","useQuery","useLazyQuery","useLazyQuerySubscription","useQueryState","useQuerySubscription","capitalize","isMutationDefinition","useMutation","isInfiniteQueryDefinition","useInfiniteQuery","useInfiniteQuerySubscription","useInfiniteQueryState","__reExport","react_exports","import_toolkit","React","ApiProvider","props","context","_formatProdErrorMessage","store","gDM","createApi","reactHooksModule"]}
Index: node_modules/@reduxjs/toolkit/dist/query/react/index.d.mts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,980 @@
+import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
+import { QueryDefinition, TSHelpersId, TSHelpersOverride, QuerySubState, ResultTypeFrom, QueryStatus, QueryArgFrom, SkipToken, SubscriptionOptions, TSHelpersNoInfer, QueryActionCreatorResult, MutationDefinition, MutationResultSelectorResult, MutationActionCreatorResult, InfiniteQueryDefinition, InfiniteQuerySubState, PageParamFrom, InfiniteQueryArgFrom, InfiniteQueryActionCreatorResult, BaseQueryFn, EndpointDefinitions, DefinitionType, QueryKeys, PrefetchOptions, Module, Api, setupListeners } from '@reduxjs/toolkit/query';
+export * from '@reduxjs/toolkit/query';
+import * as react_redux from 'react-redux';
+import { ReactReduxContextValue } from 'react-redux';
+import { CreateSelectorFunction } from 'reselect';
+import * as React from 'react';
+import { Context } from 'react';
+
+type InfiniteData<DataType, PageParam> = {
+    pages: Array<DataType>;
+    pageParams: Array<PageParam>;
+};
+type InfiniteQueryDirection = 'forward' | 'backward';
+
+export declare const UNINITIALIZED_VALUE: unique symbol;
+type UninitializedValue = typeof UNINITIALIZED_VALUE;
+
+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>;
+};
+type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
+    useInfiniteQuery: UseInfiniteQuery<Definition>;
+    useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;
+    useInfiniteQueryState: UseInfiniteQueryState<Definition>;
+};
+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
+ */
+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>;
+type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
+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
+ */
+type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
+type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+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>
+];
+type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
+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>;
+};
+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
+ */
+type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [
+    LazyQueryTrigger<D>,
+    QueryArgFrom<D> | UninitializedValue,
+    {
+        reset: () => void;
+    }
+];
+type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+/**
+ * @internal
+ */
+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
+ */
+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
+ */
+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>;
+type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+/**
+ * @internal
+ */
+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
+ */
+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>;
+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.
+ */
+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;
+};
+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>;
+};
+type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
+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;
+};
+type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
+type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;
+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
+ */
+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'>;
+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
+ */
+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>;
+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
+ */
+type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;
+type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;
+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>;
+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>;
+};
+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>;
+type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;
+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;
+};
+type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
+type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
+    selectFromResult?: MutationStateSelector<R, D>;
+    fixedCacheKey?: string;
+};
+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.
+ */
+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
+ */
+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>];
+type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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>;
+};
+type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+
+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>>>;
+};
+type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = QueryHookNames<Definitions> & LazyQueryHookNames<Definitions> & InfiniteQueryHookNames<Definitions> & MutationHookNames<Definitions>;
+
+export declare const reactHooksModuleName: unique symbol;
+type ReactHooksModule = typeof reactHooksModuleName;
+declare module '@reduxjs/toolkit/query' {
+    interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, 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 react_redux;
+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`
+ */
+declare const reactHooksModule: ({ batch, hooks, createSelector, unstable__sideEffectsInRender, ...rest }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
+
+/**
+ * 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.
+ */
+declare function ApiProvider(props: {
+    children: any;
+    api: Api<any, {}, any, any>;
+    setupListeners?: Parameters<typeof setupListeners>[1] | false;
+    context?: Context<ReactReduxContextValue | null>;
+}): React.JSX.Element;
+
+declare const createApi: _reduxjs_toolkit_query.CreateApi<typeof _reduxjs_toolkit_query.coreModuleName | typeof reactHooksModuleName>;
+
+export { ApiProvider, type TypedInfiniteQueryStateSelector, type TypedLazyInfiniteQueryTrigger, type TypedLazyQueryTrigger, type TypedMutationTrigger, type TypedQueryStateSelector, type TypedUseInfiniteQuery, type TypedUseInfiniteQueryHookResult, type TypedUseInfiniteQueryState, type TypedUseInfiniteQueryStateOptions, type TypedUseInfiniteQueryStateResult, type TypedUseInfiniteQuerySubscription, type TypedUseInfiniteQuerySubscriptionResult, type TypedUseLazyQuery, type TypedUseLazyQueryStateResult, type TypedUseLazyQuerySubscription, type TypedUseMutation, type TypedUseMutationResult, type TypedUseQuery, type TypedUseQueryHookResult, type TypedUseQueryState, type TypedUseQueryStateOptions, type TypedUseQueryStateResult, type TypedUseQuerySubscription, type TypedUseQuerySubscriptionResult, createApi, reactHooksModule };
Index: node_modules/@reduxjs/toolkit/dist/query/react/index.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,980 @@
+import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
+import { QueryDefinition, TSHelpersId, TSHelpersOverride, QuerySubState, ResultTypeFrom, QueryStatus, QueryArgFrom, SkipToken, SubscriptionOptions, TSHelpersNoInfer, QueryActionCreatorResult, MutationDefinition, MutationResultSelectorResult, MutationActionCreatorResult, InfiniteQueryDefinition, InfiniteQuerySubState, PageParamFrom, InfiniteQueryArgFrom, InfiniteQueryActionCreatorResult, BaseQueryFn, EndpointDefinitions, DefinitionType, QueryKeys, PrefetchOptions, Module, Api, setupListeners } from '@reduxjs/toolkit/query';
+export * from '@reduxjs/toolkit/query';
+import * as react_redux from 'react-redux';
+import { ReactReduxContextValue } from 'react-redux';
+import { CreateSelectorFunction } from 'reselect';
+import * as React from 'react';
+import { Context } from 'react';
+
+type InfiniteData<DataType, PageParam> = {
+    pages: Array<DataType>;
+    pageParams: Array<PageParam>;
+};
+type InfiniteQueryDirection = 'forward' | 'backward';
+
+export declare const UNINITIALIZED_VALUE: unique symbol;
+type UninitializedValue = typeof UNINITIALIZED_VALUE;
+
+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>;
+};
+type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
+    useInfiniteQuery: UseInfiniteQuery<Definition>;
+    useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;
+    useInfiniteQueryState: UseInfiniteQueryState<Definition>;
+};
+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
+ */
+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>;
+type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
+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
+ */
+type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
+type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+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>
+];
+type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
+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>;
+};
+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
+ */
+type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [
+    LazyQueryTrigger<D>,
+    QueryArgFrom<D> | UninitializedValue,
+    {
+        reset: () => void;
+    }
+];
+type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+/**
+ * @internal
+ */
+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
+ */
+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
+ */
+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>;
+type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+/**
+ * @internal
+ */
+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
+ */
+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>;
+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.
+ */
+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;
+};
+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>;
+};
+type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
+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;
+};
+type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
+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.
+ */
+type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
+type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;
+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
+ */
+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'>;
+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
+ */
+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>;
+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
+ */
+type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;
+type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;
+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>;
+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>;
+};
+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>;
+type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;
+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;
+};
+type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
+type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
+    selectFromResult?: MutationStateSelector<R, D>;
+    fixedCacheKey?: string;
+};
+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.
+ */
+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
+ */
+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>];
+type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+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>;
+};
+type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
+
+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>>>;
+};
+type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = QueryHookNames<Definitions> & LazyQueryHookNames<Definitions> & InfiniteQueryHookNames<Definitions> & MutationHookNames<Definitions>;
+
+export declare const reactHooksModuleName: unique symbol;
+type ReactHooksModule = typeof reactHooksModuleName;
+declare module '@reduxjs/toolkit/query' {
+    interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, 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 react_redux;
+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`
+ */
+declare const reactHooksModule: ({ batch, hooks, createSelector, unstable__sideEffectsInRender, ...rest }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
+
+/**
+ * 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.
+ */
+declare function ApiProvider(props: {
+    children: any;
+    api: Api<any, {}, any, any>;
+    setupListeners?: Parameters<typeof setupListeners>[1] | false;
+    context?: Context<ReactReduxContextValue | null>;
+}): React.JSX.Element;
+
+declare const createApi: _reduxjs_toolkit_query.CreateApi<typeof _reduxjs_toolkit_query.coreModuleName | typeof reactHooksModuleName>;
+
+export { ApiProvider, type TypedInfiniteQueryStateSelector, type TypedLazyInfiniteQueryTrigger, type TypedLazyQueryTrigger, type TypedMutationTrigger, type TypedQueryStateSelector, type TypedUseInfiniteQuery, type TypedUseInfiniteQueryHookResult, type TypedUseInfiniteQueryState, type TypedUseInfiniteQueryStateOptions, type TypedUseInfiniteQueryStateResult, type TypedUseInfiniteQuerySubscription, type TypedUseInfiniteQuerySubscriptionResult, type TypedUseLazyQuery, type TypedUseLazyQueryStateResult, type TypedUseLazyQuerySubscription, type TypedUseMutation, type TypedUseMutationResult, type TypedUseQuery, type TypedUseQueryHookResult, type TypedUseQueryState, type TypedUseQueryStateOptions, type TypedUseQueryStateResult, type TypedUseQuerySubscription, type TypedUseQuerySubscriptionResult, createApi, reactHooksModule };
Index: node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.browser.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+import{buildCreateApi as ue,coreModule as ye,copyWithStructuralSharing as oe,setupListeners as pe,QueryStatus as fe,skipToken as b}from"@reduxjs/toolkit/query";import"@reduxjs/toolkit";import{batch as Ce,useDispatch as Ne,useSelector as Le,useStore as He}from"react-redux";import{createSelector as ze}from"reselect";function _(e){return e.replace(e[0],e[0].toUpperCase())}var he="query",Ie="mutation",Ue="infinitequery";function Qe(e){return e.type===he}function ce(e){return e.type===Ie}function $(e){return e.type===Ue}function z(e,...c){return Object.assign(e,...c)}import{formatProdErrorMessage as be,formatProdErrorMessage as Ee}from"@reduxjs/toolkit";import{useEffect as x,useRef as I,useMemo as R,useContext as de,useCallback as k,useDebugValue as G,useLayoutEffect as le,useState as ne}from"react";import{shallowEqual as w,Provider as Re,ReactReduxContext as ge}from"react-redux";var j=Symbol();function Z(e){let c=I(e),g=R(()=>oe(c.current,e),[e]);return x(()=>{c.current!==g&&(c.current=g)},[g]),g}function v(e){let c=I(e);return x(()=>{w(c.current,e)||(c.current=e)},[e]),w(c.current,e)?c.current:e}var ke=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Oe=ke(),Me=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Fe=Me(),we=()=>Oe||Fe?le:x,ve=we(),Te=e=>e.isUninitialized?{...e,isUninitialized:!1,isFetching:!0,isLoading:e.data===void 0,status:fe.pending}:e;function re(e,...c){let g={};return c.forEach(A=>{g[A]=e[A]}),g}var ie=["data","status","isLoading","isSuccess","isError","error"];function De({api:e,moduleOptions:{batch:c,hooks:{useDispatch:g,useSelector:A,useStore:W},unstable__sideEffectsInRender:U,createSelector:C},serializeQueryArgs:E,context:N}){let O=U?t=>t():x,L=t=>t.current?.unsubscribe?.(),q=N.endpointDefinitions;return{buildQueryHooks:ee,buildInfiniteQueryHooks:Se,buildMutationHook:Be,usePrefetch:K};function J(t,i,p){if(i?.endpointName&&t.isUninitialized){let{endpointName:a}=i,y=q[a];p!==b&&E({queryArgs:i.originalArgs,endpointDefinition:y,endpointName:a})===E({queryArgs:p,endpointDefinition:y,endpointName:a})&&(i=void 0)}let u=t.isSuccess?t.data:i?.data;u===void 0&&(u=t.data);let s=u!==void 0,n=t.isLoading,r=(!i||i.isLoading||i.isUninitialized)&&!s&&n,o=t.isSuccess||s&&(n&&!i?.isError||t.isUninitialized);return{...t,data:u,currentData:t.data,isFetching:n,isLoading:r,isSuccess:o}}function m(t,i,p){if(i?.endpointName&&t.isUninitialized){let{endpointName:a}=i,y=q[a];p!==b&&E({queryArgs:i.originalArgs,endpointDefinition:y,endpointName:a})===E({queryArgs:p,endpointDefinition:y,endpointName:a})&&(i=void 0)}let u=t.isSuccess?t.data:i?.data;u===void 0&&(u=t.data);let s=u!==void 0,n=t.isLoading,r=(!i||i.isLoading||i.isUninitialized)&&!s&&n,o=t.isSuccess||n&&s;return{...t,data:u,currentData:t.data,isFetching:n,isLoading:r,isSuccess:o}}function K(t,i){let p=g(),u=v(i);return k((s,n)=>p(e.util.prefetch(t,s,{...u,...n})),[t,p,u])}function h(t,i,{refetchOnReconnect:p,refetchOnFocus:u,refetchOnMountOrArgChange:s,skip:n=!1,pollingInterval:r=0,skipPollingIfUnfocused:o=!1,...a}={}){let{initiate:y}=e.endpoints[t],d=g(),S=I(void 0);if(!S.current){let F=d(e.internalActions.internal_getRTKQSubscriptions());S.current=F}let f=Z(n?b:i),Q=v({refetchOnReconnect:p,refetchOnFocus:u,pollingInterval:r,skipPollingIfUnfocused:o}),T=a.initialPageParam,l=v(T),B=a.refetchCachedPages,P=v(B),D=I(void 0),{queryCacheKey:V,requestId:se}=D.current||{},ae=!1;V&&se&&(ae=S.current.isRequestSubscribed(V,se));let te=!ae&&D.current!==void 0;return O(()=>{te&&(D.current=void 0)},[te]),O(()=>{let F=D.current;if(f===b){F?.unsubscribe(),D.current=void 0;return}let Pe=D.current?.subscriptionOptions;if(!F||F.arg!==f){F?.unsubscribe();let Ae=d(y(f,{subscriptionOptions:Q,forceRefetch:s,...$(q[t])?{initialPageParam:l,refetchCachedPages:P}:{}}));D.current=Ae}else Q!==Pe&&F.updateSubscriptionOptions(Q)},[d,y,s,f,Q,te,l,P,t]),[D,d,y,Q]}function M(t,i){return(u,{skip:s=!1,selectFromResult:n}={})=>{let{select:r}=e.endpoints[t],o=Z(s?b:u),a=I(void 0),y=R(()=>C([r(o),(T,l)=>l,T=>o],i,{memoizeOptions:{resultEqualityCheck:w}}),[r,o]),d=R(()=>n?C([y],n,{devModeChecks:{identityFunctionCheck:"never"}}):y,[y,n]),S=A(T=>d(T,a.current),w),f=W(),Q=y(f.getState(),a.current);return ve(()=>{a.current=Q},[Q]),S}}function H(t){x(()=>()=>{L(t),t.current=void 0},[t])}function X(t){if(!t.current)throw new Error(be(38));return t.current.refetch()}function ee(t){let i=(s,n={})=>{let[r]=h(t,s,n);return H(r),R(()=>({refetch:()=>X(r)}),[r])},p=({refetchOnReconnect:s,refetchOnFocus:n,pollingInterval:r=0,skipPollingIfUnfocused:o=!1}={})=>{let{initiate:a}=e.endpoints[t],y=g(),[d,S]=ne(j),f=I(void 0),Q=v({refetchOnReconnect:s,refetchOnFocus:n,pollingInterval:r,skipPollingIfUnfocused:o});O(()=>{let P=f.current?.subscriptionOptions;Q!==P&&f.current?.updateSubscriptionOptions(Q)},[Q]);let T=I(Q);O(()=>{T.current=Q},[Q]);let l=k(function(P,D=!1){let V;return c(()=>{L(f),f.current=V=y(a(P,{subscriptionOptions:T.current,forceRefetch:!D})),S(P)}),V},[y,a]),B=k(()=>{f.current?.queryCacheKey&&y(e.internalActions.removeQueryResult({queryCacheKey:f.current?.queryCacheKey}))},[y]);return x(()=>()=>{L(f)},[]),x(()=>{d!==j&&!f.current&&l(d,!0)},[d,l]),R(()=>[l,d,{reset:B}],[l,d,B])},u=M(t,J);return{useQueryState:u,useQuerySubscription:i,useLazyQuerySubscription:p,useLazyQuery(s){let[n,r,{reset:o}]=p(s),a=u(r,{...s,skip:r===j}),y=R(()=>({lastArg:r}),[r]);return R(()=>[n,{...a,reset:o},y],[n,a,o,y])},useQuery(s,n){let r=i(s,n),o=u(s,{selectFromResult:s===b||n?.skip?void 0:Te,...n}),a=re(o,...ie);return G(a),R(()=>({...o,...r}),[o,r])}}}function Se(t){let i=(u,s={})=>{let[n,r,o,a]=h(t,u,s),y=I(a);O(()=>{y.current=a},[a]);let d=s.refetchCachedPages,S=v(d),f=k(function(l,B){let P;return c(()=>{L(n),n.current=P=r(o(l,{subscriptionOptions:y.current,direction:B}))}),P},[n,r,o]);H(n);let Q=Z(s.skip?b:u),T=k(l=>{if(!n.current)throw new Error(Ee(38));let B={refetchCachedPages:l?.refetchCachedPages??S};return n.current.refetch(B)},[n,S]);return R(()=>({trigger:f,refetch:T,fetchNextPage:()=>f(Q,"forward"),fetchPreviousPage:()=>f(Q,"backward")}),[T,f,Q])},p=M(t,m);return{useInfiniteQueryState:p,useInfiniteQuerySubscription:i,useInfiniteQuery(u,s){let{refetch:n,fetchNextPage:r,fetchPreviousPage:o}=i(u,s),a=p(u,{selectFromResult:u===b||s?.skip?void 0:Te,...s}),y=re(a,...ie,"hasNextPage","hasPreviousPage");return G(y),R(()=>({...a,fetchNextPage:r,fetchPreviousPage:o,refetch:n}),[a,r,o,n])}}}function Be(t){return({selectFromResult:i,fixedCacheKey:p}={})=>{let{select:u,initiate:s}=e.endpoints[t],n=g(),[r,o]=ne();x(()=>()=>{r?.arg.fixedCacheKey||r?.reset()},[r]);let a=k(function(P){let D=n(s(P,{fixedCacheKey:p}));return o(D),D},[n,s,p]),{requestId:y}=r||{},d=R(()=>u({fixedCacheKey:p,requestId:r?.requestId}),[p,r,u]),S=R(()=>i?C([d],i):d,[i,d]),f=A(S,w),Q=p==null?r?.arg.originalArgs:void 0,T=k(()=>{c(()=>{r&&o(void 0),p&&n(e.internalActions.removeMutationResult({requestId:y,fixedCacheKey:p}))})},[n,p,r,y]),l=re(f,...ie,"endpointName");G(l);let B=R(()=>({...f,originalArgs:Q,reset:T}),[f,Q,T]);return R(()=>[a,B],[a,B])}}}var xe=Symbol(),me=({batch:e=Ce,hooks:c={useDispatch:Ne,useSelector:Le,useStore:He},createSelector:g=ze,unstable__sideEffectsInRender:A=!1,...W}={})=>({name:xe,init(U,{serializeQueryArgs:C},E){let N=U,{buildQueryHooks:O,buildInfiniteQueryHooks:L,buildMutationHook:q,usePrefetch:J}=De({api:U,moduleOptions:{batch:e,hooks:c,unstable__sideEffectsInRender:A,createSelector:g},serializeQueryArgs:C,context:E});return z(N,{usePrefetch:J}),z(E,{batch:e}),{injectEndpoint(m,K){if(Qe(K)){let{useQuery:h,useLazyQuery:M,useLazyQuerySubscription:H,useQueryState:X,useQuerySubscription:ee}=O(m);z(N.endpoints[m],{useQuery:h,useLazyQuery:M,useLazyQuerySubscription:H,useQueryState:X,useQuerySubscription:ee}),U[`use${_(m)}Query`]=h,U[`useLazy${_(m)}Query`]=M}if(ce(K)){let h=q(m);z(N.endpoints[m],{useMutation:h}),U[`use${_(m)}Mutation`]=h}else if($(K)){let{useInfiniteQuery:h,useInfiniteQuerySubscription:M,useInfiniteQueryState:H}=L(m);z(N.endpoints[m],{useInfiniteQuery:h,useInfiniteQuerySubscription:M,useInfiniteQueryState:H}),U[`use${_(m)}InfiniteQuery`]=h}}}}});export*from"@reduxjs/toolkit/query";import{configureStore as qe,formatProdErrorMessage as Ke}from"@reduxjs/toolkit";import*as Y from"react";function Ve(e){let c=e.context||ge;if(de(c))throw new Error(Ke(35));let[A]=Y.useState(()=>qe({reducer:{[e.api.reducerPath]:e.api.reducer},middleware:W=>W().concat(e.api.middleware)}));return x(()=>e.setupListeners===!1?void 0:pe(A.dispatch,e.setupListeners),[e.setupListeners,A.dispatch]),Y.createElement(Re,{store:A,context:c},e.children)}var Ft=ue(ye(),me());export{Ve as ApiProvider,j as UNINITIALIZED_VALUE,Ft as createApi,me as reactHooksModule,xe as reactHooksModuleName};
+//# sourceMappingURL=rtk-query-react.browser.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.browser.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/query/react/rtkqImports.ts","../../../src/query/react/module.ts","../../../src/query/utils/capitalize.ts","../../../src/query/endpointDefinitions.ts","../../../src/query/tsHelpers.ts","../../../src/query/react/buildHooks.ts","../../../src/query/react/reactImports.ts","../../../src/query/react/reactReduxImports.ts","../../../src/query/react/constants.ts","../../../src/query/react/useSerializedStableValue.ts","../../../src/query/react/useShallowStableValue.ts","../../../src/query/react/index.ts","../../../src/query/react/ApiProvider.tsx"],"sourcesContent":["export { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from '@reduxjs/toolkit/query';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Api, BaseQueryFn, EndpointDefinitions, InfiniteQueryDefinition, Module, MutationDefinition, PrefetchOptions, QueryArgFrom, QueryDefinition, QueryKeys } from '@reduxjs/toolkit/query';\nimport { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from 'react-redux';\nimport type { CreateSelectorFunction } from 'reselect';\nimport { createSelector as _createSelector } from 'reselect';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { safeAssign } from '../tsHelpers';\nimport { capitalize, countObjectKeys } from '../utils';\nimport type { InfiniteQueryHooks, MutationHooks, QueryHooks } from './buildHooks';\nimport { buildHooks } from './buildHooks';\nimport type { HooksWithUniqueNames } from './namedHooks';\nexport const reactHooksModuleName = /* @__PURE__ */Symbol();\nexport type ReactHooksModule = typeof reactHooksModuleName;\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  ReducerPath extends string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  TagTypes extends string> {\n    [reactHooksModuleName]: {\n      /**\n       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n       */\n      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 };\n      /**\n       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n       */\n      usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;\n    } & HooksWithUniqueNames<Definitions>;\n  }\n}\ntype RR = typeof import('react-redux');\nexport interface ReactHooksModuleOptions {\n  /**\n   * The hooks from React Redux to be used\n   */\n  hooks?: {\n    /**\n     * The version of the `useDispatch` hook to be used\n     */\n    useDispatch: RR['useDispatch'];\n    /**\n     * The version of the `useSelector` hook to be used\n     */\n    useSelector: RR['useSelector'];\n    /**\n     * The version of the `useStore` hook to be used\n     */\n    useStore: RR['useStore'];\n  };\n  /**\n   * The version of the `batchedUpdates` function to be used\n   */\n  batch?: RR['batch'];\n  /**\n   * Enables performing asynchronous tasks immediately within a render.\n   *\n   * @example\n   *\n   * ```ts\n   * import {\n   *   buildCreateApi,\n   *   coreModule,\n   *   reactHooksModule\n   * } from '@reduxjs/toolkit/query/react'\n   *\n   * const createApi = buildCreateApi(\n   *   coreModule(),\n   *   reactHooksModule({ unstable__sideEffectsInRender: true })\n   * )\n   * ```\n   */\n  unstable__sideEffectsInRender?: boolean;\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n *  @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n  batch = rrBatch,\n  hooks = {\n    useDispatch: rrUseDispatch,\n    useSelector: rrUseSelector,\n    useStore: rrUseStore\n  },\n  createSelector = _createSelector,\n  unstable__sideEffectsInRender = false,\n  ...rest\n}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {\n  if (process.env.NODE_ENV !== 'production') {\n    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const;\n    let warned = false;\n    for (const hookName of hookNames) {\n      // warn for old hook options\n      if (countObjectKeys(rest) > 0) {\n        if ((rest as Partial<typeof hooks>)[hookName]) {\n          if (!warned) {\n            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 } })`');\n            warned = true;\n          }\n        }\n        // migrate\n        // @ts-ignore\n        hooks[hookName] = rest[hookName];\n      }\n      // then make sure we have them all\n      if (typeof hooks[hookName] !== 'function') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(36) : `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.`);\n      }\n    }\n  }\n  return {\n    name: reactHooksModuleName,\n    init(api, {\n      serializeQueryArgs\n    }, context) {\n      const anyApi = api as any as Api<any, Record<string, any>, any, any, ReactHooksModule>;\n      const {\n        buildQueryHooks,\n        buildInfiniteQueryHooks,\n        buildMutationHook,\n        usePrefetch\n      } = buildHooks({\n        api,\n        moduleOptions: {\n          batch,\n          hooks,\n          unstable__sideEffectsInRender,\n          createSelector\n        },\n        serializeQueryArgs,\n        context\n      });\n      safeAssign(anyApi, {\n        usePrefetch\n      });\n      safeAssign(context, {\n        batch\n      });\n      return {\n        injectEndpoint(endpointName, definition) {\n          if (isQueryDefinition(definition)) {\n            const {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            } = buildQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            });\n            (api as any)[`use${capitalize(endpointName)}Query`] = useQuery;\n            (api as any)[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;\n          }\n          if (isMutationDefinition(definition)) {\n            const useMutation = buildMutationHook(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useMutation\n            });\n            (api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation;\n          } else if (isInfiniteQueryDefinition(definition)) {\n            const {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            } = buildInfiniteQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            });\n            (api as any)[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;\n          }\n        }\n      };\n    }\n  };\n};","export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase());\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Selector, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport 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';\nimport { QueryStatus, skipToken } from './rtkqImports';\nimport type { DependencyList } from 'react';\nimport { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/index';\nimport type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index';\nimport type { UninitializedValue } from './constants';\nimport { UNINITIALIZED_VALUE } from './constants';\nimport type { ReactHooksModuleOptions } from './module';\nimport { useStableQueryArgs } from './useSerializedStableValue';\nimport { useShallowStableValue } from './useShallowStableValue';\nimport type { InfiniteQueryDirection } from '../core/apiState';\nimport { isInfiniteQueryDefinition } from '../endpointDefinitions';\nimport type { StartInfiniteQueryActionCreator } from '../core/buildInitiate';\n\n// Copy-pasted from React-Redux\nconst canUseDOM = () => !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nconst isDOM = /* @__PURE__ */canUseDOM();\n\n// Under React Native, we know that we always want to use useLayoutEffect\n\nconst isRunningInReactNative = () => typeof navigator !== 'undefined' && navigator.product === 'ReactNative';\nconst isReactNative = /* @__PURE__ */isRunningInReactNative();\nconst getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;\nexport const useIsomorphicLayoutEffect = /* @__PURE__ */getUseIsomorphicLayoutEffect();\nexport type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  useQuery: UseQuery<Definition>;\n  useLazyQuery: UseLazyQuery<Definition>;\n  useQuerySubscription: UseQuerySubscription<Definition>;\n  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;\n  useQueryState: UseQueryState<Definition>;\n};\nexport type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  useInfiniteQuery: UseInfiniteQuery<Definition>;\n  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;\n  useInfiniteQueryState: UseInfiniteQueryState<Definition>;\n};\nexport type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  useMutation: UseMutation<Definition>;\n};\n\n/**\n * 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.\n *\n * 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.\n *\n * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuery` hook in userland code.\n */\nexport type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;\nexport type UseQuerySubscriptionOptions = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n};\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;\nexport type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {\n  lastArg: QueryArgFrom<D>;\n};\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - 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\n *\n * #### Note\n *\n * 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.\n */\nexport 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>];\nexport type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useLazyQuery` hook in userland code.\n */\nexport type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\nexport type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;\n};\nexport type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - 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\n */\nexport type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, {\n  reset: () => void;\n}];\nexport type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   title: string\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * type SelectedResult = Pick<PostsApiResponse, 'posts'>\n *\n * const postsApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, QueryArgument>({\n *       query: (limit = 5) => `?limit=${limit}&select=title`,\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = postsApiSlice\n *\n * function PostById({ id }: { id: number }) {\n *   const { post } = useGetPostsQuery(undefined, {\n *     selectFromResult: (state) => ({\n *       post: state.data?.posts.find((post) => post.id === id),\n *     }),\n *   })\n *\n *   return <li>{post?.title}</li>\n * }\n *\n * const EMPTY_ARRAY: Post[] = []\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n *\n * function PostsList() {\n *   const { posts } = useGetPostsQuery(undefined, {\n *     selectFromResult: typedSelectFromResult,\n *   })\n *\n *   return (\n *     <div>\n *       <ul>\n *         {posts.map((post) => (\n *           <PostById key={post.id} id={post.id} />\n *         ))}\n *       </ul>\n *     </div>\n *   )\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.3.0\n * @public\n */\nexport 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>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: QueryStateSelector<R, D>;\n};\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * <caption>#### __Create a `useQuery` hook with default options__</caption>\n *\n * ```ts\n * import type {\n *   SubscriptionOptions,\n *   TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   name: string\n * }\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   tagTypes: ['Post'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<Post[], void>({\n *       query: () => 'posts',\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = api\n *\n * export const useGetPostsQueryWithDefaults = <\n *   SelectedResult extends Record<string, any>,\n * >(\n *   overrideOptions: TypedUseQueryStateOptions<\n *     Post[],\n *     void,\n *     ReturnType<typeof fetchBaseQuery>,\n *     SelectedResult\n *   > &\n *     SubscriptionOptions,\n * ) =>\n *   useGetPostsQuery(undefined, {\n *     // Insert default options here\n *\n *     refetchOnMountOrArgChange: true,\n *     refetchOnFocus: true,\n *     ...overrideOptions,\n *   })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.2.8\n * @public\n */\nexport 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>;\nexport type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;\ntype UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: ResultTypeFrom<D>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n};\ntype UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}>;\ntype UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n}>;\ntype UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n  currentData: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isError: true;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;\ntype UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;\n};\nexport type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  initialPageParam?: PageParamFrom<D>;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   *\n   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).\n   * It can be overridden on a per-call basis using the `refetch()` method.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  refetch: (options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>) => InfiniteQueryActionCreatorResult<D>;\n  trigger: LazyInfiniteQueryTrigger<D>;\n  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;\nexport 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>>;\n\n/**\n * 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.\n *\n * 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.\n *\n *  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.\n *\n * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.\n *\n * 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.\n *\n * 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.\n *\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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'>;\nexport type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;\nexport type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;\nexport 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>;\nexport type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: InfiniteQueryStateSelector<R, D>;\n};\nexport 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>;\nexport type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;\nexport 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>;\ntype UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n};\ntype UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n} | ({\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({\n  isError: true;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;\nexport type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  selectFromResult?: MutationStateSelector<R, D>;\n  fixedCacheKey?: string;\n};\nexport type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {\n  originalArgs?: QueryArgFrom<D>;\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\n\n/**\n * 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.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>];\nexport type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {\n  /**\n   * Triggers the mutation and returns a Promise.\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;\n};\nexport type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector<any, any> = selected => {\n  if (selected.isUninitialized) {\n    return {\n      ...selected,\n      isUninitialized: false,\n      isFetching: true,\n      isLoading: selected.data !== undefined ? false : true,\n      // This is the one place where we still have to use `QueryStatus` as an enum,\n      // since it's the only reference in the React package and not in the core.\n      status: QueryStatus.pending\n    } as any;\n  }\n  return selected;\n};\nfunction pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {\n  const ret: any = {};\n  keys.forEach(key => {\n    ret[key] = obj[key];\n  });\n  return ret;\n}\nconst COMMON_HOOK_DEBUG_FIELDS = ['data', 'status', 'isLoading', 'isSuccess', 'isError', 'error'] as const;\ntype GenericPrefetchThunk = (endpointName: any, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, UnknownAction>;\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks<Definitions extends EndpointDefinitions>({\n  api,\n  moduleOptions: {\n    batch,\n    hooks: {\n      useDispatch,\n      useSelector,\n      useStore\n    },\n    unstable__sideEffectsInRender,\n    createSelector\n  },\n  serializeQueryArgs,\n  context\n}: {\n  api: Api<any, Definitions, any, any, CoreModule>;\n  moduleOptions: Required<ReactHooksModuleOptions>;\n  serializeQueryArgs: SerializeQueryArgs<any>;\n  context: ApiContext<Definitions>;\n}) {\n  const usePossiblyImmediateEffect: (effect: () => void | undefined, deps?: DependencyList) => void = unstable__sideEffectsInRender ? cb => cb() : useEffect;\n  type UnsubscribePromiseRef = React.RefObject<{\n    unsubscribe?: () => void;\n  } | undefined>;\n  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) => ref.current?.unsubscribe?.();\n  const endpointDefinitions = context.endpointDefinitions;\n  return {\n    buildQueryHooks,\n    buildInfiniteQueryHooks,\n    buildMutationHook,\n    usePrefetch\n  };\n  function queryStatePreSelector(currentState: QueryResultSelectorResult<any>, lastResult: UseQueryStateDefaultResult<any> | undefined, queryArgs: any): UseQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n\n    // isSuccess = true when data is present and we're not refetching after an error.\n    // That includes cases where the _current_ item is either actively\n    // fetching or about to fetch due to an uninitialized entry.\n    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseQueryStateDefaultResult<any>;\n  }\n  function infiniteQueryStatePreSelector(currentState: InfiniteQueryResultSelectorResult<any>, lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined, queryArgs: any): UseInfiniteQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n    // isSuccess = true when data is present\n    const isSuccess = currentState.isSuccess || isFetching && hasData;\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseInfiniteQueryStateDefaultResult<any>;\n  }\n  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions) {\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n    const stableDefaultOptions = useShallowStableValue(defaultOptions);\n    return useCallback((arg: any, options?: PrefetchOptions) => dispatch((api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n      ...stableDefaultOptions,\n      ...options\n    })), [endpointName, dispatch, stableDefaultOptions]);\n  }\n  function useQuerySubscriptionCommonImpl<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(endpointName: string, arg: unknown | SkipToken, {\n    refetchOnReconnect,\n    refetchOnFocus,\n    refetchOnMountOrArgChange,\n    skip = false,\n    pollingInterval = 0,\n    skipPollingIfUnfocused = false,\n    ...rest\n  }: UseQuerySubscriptionOptions = {}) {\n    const {\n      initiate\n    } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n\n    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.\n    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(undefined);\n    if (!subscriptionSelectorsRef.current) {\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n    You must add the middleware for RTK-Query to function correctly!`);\n        }\n      }\n      subscriptionSelectorsRef.current = returnedValue as unknown as SubscriptionSelectors;\n    }\n    const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n    const stableSubscriptionOptions = useShallowStableValue({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval,\n      skipPollingIfUnfocused\n    });\n    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>).initialPageParam;\n    const stableInitialPageParam = useShallowStableValue(initialPageParam);\n    const refetchCachedPages = (rest as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);\n\n    /**\n     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n     */\n    const promiseRef = useRef<T | undefined>(undefined);\n    let {\n      queryCacheKey,\n      requestId\n    } = promiseRef.current || {};\n\n    // HACK We've saved the middleware subscription lookup callbacks into a ref,\n    // so we can directly check here if the subscription exists for this query.\n    let currentRenderHasSubscription = false;\n    if (queryCacheKey && requestId) {\n      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);\n    }\n    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== undefined;\n    usePossiblyImmediateEffect((): void | undefined => {\n      if (subscriptionRemoved) {\n        promiseRef.current = undefined;\n      }\n    }, [subscriptionRemoved]);\n    usePossiblyImmediateEffect((): void | undefined => {\n      const lastPromise = promiseRef.current;\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {\n        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n        console.log(subscriptionRemoved);\n      }\n      if (stableArg === skipToken) {\n        lastPromise?.unsubscribe();\n        promiseRef.current = undefined;\n        return;\n      }\n      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n      if (!lastPromise || lastPromise.arg !== stableArg) {\n        lastPromise?.unsubscribe();\n        const promise = dispatch(initiate(stableArg, {\n          subscriptionOptions: stableSubscriptionOptions,\n          forceRefetch: refetchOnMountOrArgChange,\n          ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {\n            initialPageParam: stableInitialPageParam,\n            refetchCachedPages: stableRefetchCachedPages\n          } : {})\n        }));\n        promiseRef.current = promise as T;\n      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\n      }\n    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);\n    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const;\n  }\n  function buildUseQueryState(endpointName: string, preSelector: typeof queryStatePreSelector | typeof infiniteQueryStatePreSelector) {\n    const useQueryState = (arg: any, {\n      skip = false,\n      selectFromResult\n    }: UseQueryStateOptions<any, any> | UseInfiniteQueryStateOptions<any, any> = {}) => {\n      const {\n        select\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n      type ApiRootState = Parameters<ReturnType<typeof select>>[0];\n      const lastValue = useRef<any>(undefined);\n      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(() =>\n      // Normally ts-ignores are bad and should be avoided, but we're\n      // already casting this selector to be `Selector<any>` anyway,\n      // so the inconsistencies don't matter here\n      // @ts-ignore\n      createSelector([\n      // @ts-ignore\n      select(stableArg), (_: ApiRootState, lastResult: any) => lastResult, (_: ApiRootState) => stableArg], preSelector, {\n        memoizeOptions: {\n          resultEqualityCheck: shallowEqual\n        }\n      }), [select, stableArg]);\n      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {\n        devModeChecks: {\n          identityFunctionCheck: 'never'\n        }\n      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);\n      const currentState = useSelector((state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current), shallowEqual);\n      const store = useStore<RootState<Definitions, any, any>>();\n      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);\n      useIsomorphicLayoutEffect(() => {\n        lastValue.current = newLastValue;\n      }, [newLastValue]);\n      return currentState;\n    };\n    return useQueryState;\n  }\n  function usePromiseRefUnsubscribeOnUnmount(promiseRef: UnsubscribePromiseRef) {\n    useEffect(() => {\n      return () => {\n        unsubscribePromiseRef(promiseRef)\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        ;\n        (promiseRef.current as any) = undefined;\n      };\n    }, [promiseRef]);\n  }\n  function refetchOrErrorIfUnmounted<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(promiseRef: React.RefObject<T | undefined>): T {\n    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(38) : 'Cannot refetch a query that has not been started yet.');\n    return promiseRef.current.refetch() as T;\n  }\n  function buildQueryHooks(endpointName: string): QueryHooks<any> {\n    const useQuerySubscription: UseQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef] = useQuerySubscriptionCommonImpl<QueryActionCreatorResult<any>>(endpointName, arg, options);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      return useMemo(() => ({\n        /**\n         * A method to manually refetch data for the query\n         */\n        refetch: () => refetchOrErrorIfUnmounted(promiseRef)\n      }), [promiseRef]);\n    };\n    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false\n    } = {}) => {\n      const {\n        initiate\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE);\n\n      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n      /**\n       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n       */\n      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(undefined);\n      const stableSubscriptionOptions = useShallowStableValue({\n        refetchOnReconnect,\n        refetchOnFocus,\n        pollingInterval,\n        skipPollingIfUnfocused\n      });\n      usePossiblyImmediateEffect(() => {\n        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n        if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n          promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);\n        }\n      }, [stableSubscriptionOptions]);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n      const trigger = useCallback(function (arg: any, preferCacheValue = false) {\n        let promise: QueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch(initiate(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            forceRefetch: !preferCacheValue\n          }));\n          setArg(arg);\n        });\n        return promise!;\n      }, [dispatch, initiate]);\n      const reset = useCallback(() => {\n        if (promiseRef.current?.queryCacheKey) {\n          dispatch(api.internalActions.removeQueryResult({\n            queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey\n          }));\n        }\n      }, [dispatch]);\n\n      /* cleanup on unmount */\n      useEffect(() => {\n        return () => {\n          unsubscribePromiseRef(promiseRef);\n        };\n      }, []);\n\n      /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n      useEffect(() => {\n        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n          trigger(arg, true);\n        }\n      }, [arg, trigger]);\n      return useMemo(() => [trigger, arg, {\n        reset\n      }] as const, [trigger, arg, reset]);\n    };\n    const useQueryState: UseQueryState<any> = buildUseQueryState(endpointName, queryStatePreSelector);\n    return {\n      useQueryState,\n      useQuerySubscription,\n      useLazyQuerySubscription,\n      useLazyQuery(options) {\n        const [trigger, arg, {\n          reset\n        }] = useLazyQuerySubscription(options);\n        const queryStateResults = useQueryState(arg, {\n          ...options,\n          skip: arg === UNINITIALIZED_VALUE\n        });\n        const info = useMemo(() => ({\n          lastArg: arg\n        }), [arg]);\n        return useMemo(() => [trigger, {\n          ...queryStateResults,\n          reset\n        }, info], [trigger, queryStateResults, reset, info]);\n      },\n      useQuery(arg, options) {\n        const querySubscriptionResults = useQuerySubscription(arg, options);\n        const queryStateResults = useQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          ...querySubscriptionResults\n        }), [queryStateResults, querySubscriptionResults]);\n      }\n    };\n  }\n  function buildInfiniteQueryHooks(endpointName: string): InfiniteQueryHooks<any> {\n    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(endpointName, arg, options);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n\n      // Extract and stabilize the hook-level refetchCachedPages option\n      const hookRefetchCachedPages = (options as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);\n      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(function (arg: unknown, direction: 'forward' | 'backward') {\n        let promise: InfiniteQueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch((initiate as StartInfiniteQueryActionCreator<any>)(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            direction\n          }));\n        });\n        return promise!;\n      }, [promiseRef, dispatch, initiate]);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);\n      const refetch = useCallback((options?: Pick<UseInfiniteQuerySubscriptionOptions<any>, 'refetchCachedPages'>) => {\n        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(38) : 'Cannot refetch a query that has not been started yet.');\n        // Merge per-call options with hook-level default\n        const mergedOptions = {\n          refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages\n        };\n        return promiseRef.current.refetch(mergedOptions);\n      }, [promiseRef, stableHookRefetchCachedPages]);\n      return useMemo(() => {\n        const fetchNextPage = () => {\n          return trigger(stableArg, 'forward');\n        };\n        const fetchPreviousPage = () => {\n          return trigger(stableArg, 'backward');\n        };\n        return {\n          trigger,\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        };\n      }, [refetch, trigger, stableArg]);\n    };\n    const useInfiniteQueryState: UseInfiniteQueryState<any> = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);\n    return {\n      useInfiniteQueryState,\n      useInfiniteQuerySubscription,\n      useInfiniteQuery(arg, options) {\n        const {\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        } = useInfiniteQuerySubscription(arg, options);\n        const queryStateResults = useInfiniteQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, 'hasNextPage', 'hasPreviousPage');\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          fetchNextPage,\n          fetchPreviousPage,\n          refetch\n        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);\n      }\n    };\n  }\n  function buildMutationHook(name: string): UseMutation<any> {\n    return ({\n      selectFromResult,\n      fixedCacheKey\n    } = {}) => {\n      const {\n        select,\n        initiate\n      } = api.endpoints[name] as ApiEndpointMutation<MutationDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>();\n      useEffect(() => () => {\n        if (!promise?.arg.fixedCacheKey) {\n          promise?.reset();\n        }\n      }, [promise]);\n      const triggerMutation = useCallback(function (arg: Parameters<typeof initiate>['0']) {\n        const promise = dispatch(initiate(arg, {\n          fixedCacheKey\n        }));\n        setPromise(promise);\n        return promise;\n      }, [dispatch, initiate, fixedCacheKey]);\n      const {\n        requestId\n      } = promise || {};\n      const selectDefaultResult = useMemo(() => select({\n        fixedCacheKey,\n        requestId: promise?.requestId\n      }), [fixedCacheKey, promise, select]);\n      const mutationSelector = useMemo((): Selector<RootState<Definitions, any, any>, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);\n      const currentState = useSelector(mutationSelector, shallowEqual);\n      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;\n      const reset = useCallback(() => {\n        batch(() => {\n          if (promise) {\n            setPromise(undefined);\n          }\n          if (fixedCacheKey) {\n            dispatch(api.internalActions.removeMutationResult({\n              requestId,\n              fixedCacheKey\n            }));\n          }\n        });\n      }, [dispatch, fixedCacheKey, promise, requestId]);\n      const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, 'endpointName');\n      useDebugValue(debugValue);\n      const finalState = useMemo(() => ({\n        ...currentState,\n        originalArgs,\n        reset\n      }), [currentState, originalArgs, reset]);\n      return useMemo(() => [triggerMutation, finalState] as const, [triggerMutation, finalState]);\n    };\n  }\n}","export { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from 'react';","export { shallowEqual, Provider, ReactReduxContext } from 'react-redux';","export const UNINITIALIZED_VALUE = Symbol();\nexport type UninitializedValue = typeof UNINITIALIZED_VALUE;","import { useEffect, useRef, useMemo } from './reactImports';\nimport { copyWithStructuralSharing } from './rtkqImports';\nexport function useStableQueryArgs<T>(queryArgs: T) {\n  const cache = useRef(queryArgs);\n  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);\n  useEffect(() => {\n    if (cache.current !== copy) {\n      cache.current = copy;\n    }\n  }, [copy]);\n  return copy;\n}","import { useEffect, useRef } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nexport function useShallowStableValue<T>(value: T) {\n  const cache = useRef(value);\n  useEffect(() => {\n    if (!shallowEqual(cache.current, value)) {\n      cache.current = value;\n    }\n  }, [value]);\n  return shallowEqual(cache.current, value) ? cache.current : value;\n}","// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nimport { buildCreateApi, coreModule } from './rtkqImports';\nimport { reactHooksModule, reactHooksModuleName } from './module';\nexport * from '@reduxjs/toolkit/query';\nexport { ApiProvider } from './ApiProvider';\nconst createApi = /* @__PURE__ */buildCreateApi(coreModule(), reactHooksModule());\nexport 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';\nexport { UNINITIALIZED_VALUE } from './constants';\nexport { createApi, reactHooksModule, reactHooksModuleName };","import { configureStore, formatProdErrorMessage as _formatProdErrorMessage } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport { useContext, useEffect } from './reactImports';\nimport * as React from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { Provider, ReactReduxContext } from './reactReduxImports';\nimport { setupListeners } from './rtkqImports';\nimport type { Api } from '@reduxjs/toolkit/query';\n\n/**\n * Can be used as a `Provider` if you **do not already have a Redux store**.\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Basic usage - wrap your App with ApiProvider\"\n * import * as React from 'react';\n * import { ApiProvider } from '@reduxjs/toolkit/query/react';\n * import { Pokemon } from './features/Pokemon';\n *\n * function App() {\n *   return (\n *     <ApiProvider api={api}>\n *       <Pokemon />\n *     </ApiProvider>\n *   );\n * }\n * ```\n *\n * @remarks\n * Using this together with an existing redux store, both will\n * conflict with each other - please use the traditional redux setup\n * in that case.\n */\nexport function ApiProvider(props: {\n  children: any;\n  api: Api<any, {}, any, any>;\n  setupListeners?: Parameters<typeof setupListeners>[1] | false;\n  context?: Context<ReactReduxContextValue | null>;\n}) {\n  const context = props.context || ReactReduxContext;\n  const existingContext = useContext(context);\n  if (existingContext) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(35) : 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.');\n  }\n  const [store] = React.useState(() => configureStore({\n    reducer: {\n      [props.api.reducerPath]: props.api.reducer\n    },\n    middleware: gDM => gDM().concat(props.api.middleware)\n  }));\n  // Adds the event listeners for online/offline/focus/etc\n  useEffect((): undefined | (() => void) => props.setupListeners === false ? undefined : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);\n  return <Provider store={store} context={context}>\n      {props.children}\n    </Provider>;\n}"],"mappings":"AAAA,OAAS,kBAAAA,GAAgB,cAAAC,GAAY,6BAAAC,GAA2B,kBAAAC,GAAgB,eAAAC,GAAa,aAAAC,MAAiB,yBCA9G,MAAkE,mBAElE,OAAS,SAASC,GAAS,eAAeC,GAAe,eAAeC,GAAe,YAAYC,OAAkB,cAErH,OAAS,kBAAkBC,OAAuB,WCJ3C,SAASC,EAAWC,EAAa,CACtC,OAAOA,EAAI,QAAQA,EAAI,CAAC,EAAGA,EAAI,CAAC,EAAE,YAAY,CAAC,CACjD,CCuYO,IAAMC,GAAiB,QACjBC,GAAoB,WACpBC,GAAyB,gBA+c/B,SAASC,GAAkB,EAA8G,CAC9I,OAAO,EAAE,OAASH,EACpB,CACO,SAASI,GAAqB,EAAiH,CACpJ,OAAO,EAAE,OAASH,EACpB,CACO,SAASI,EAA0B,EAA2H,CACnK,OAAO,EAAE,OAASH,EACpB,CC91BO,SAASI,EAA6BC,KAAcC,EAAqC,CAC9F,OAAO,OAAO,OAAOD,EAAQ,GAAGC,CAAI,CACtC,CCNA,OAA4D,0BAA0BC,GAA0B,0BAA0BC,OAAgC,mBCA1K,OAAS,aAAAC,EAAW,UAAAC,EAAQ,WAAAC,EAAS,cAAAC,GAAY,eAAAC,EAAa,iBAAAC,EAAe,mBAAAC,GAAiB,YAAAC,OAAgB,QCA9G,OAAS,gBAAAC,EAAc,YAAAC,GAAU,qBAAAC,OAAyB,cCAnD,IAAMC,EAAsB,OAAO,ECEnC,SAASC,EAAsBC,EAAc,CAClD,IAAMC,EAAQC,EAAOF,CAAS,EACxBG,EAAOC,EAAQ,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reateApi","coreModule","copyWithStructuralSharing","setupListeners","QueryStatus","skipToken","rrBatch","rrUseDispatch","rrUseSelector","rrUseStore","_createSelector","capitalize","str","ENDPOINT_QUERY","ENDPOINT_MUTATION","ENDPOINT_INFINITEQUERY","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","safeAssign","target","args","_formatProdErrorMessage2","_formatProdErrorMessage3","useEffect","useRef","useMemo","useContext","useCallback","useDebugValue","useLayoutEffect","useState","shallowEqual","Provider","ReactReduxContext","UNINITIALIZED_VALUE","useStableQueryArgs","queryArgs","cache","useRef","copy","useMemo","copyWithStructuralSharing","useEffect","useShallowStableValue","value","cache","useRef","useEffect","shallowEqual","canUseDOM","isDOM","isRunningInReactNative","isReactNative","getUseIsomorphicLayoutEffect","useLayoutEffect","useEffect","useIsomorphicLayoutEffect","noPendingQueryStateSelector","selected","QueryStatus","pick","obj","keys","ret","key","COMMON_HOOK_DEBUG_FIELDS","buildHooks","api","batch","useDispatch","useSelector","useStore","unstable__sideEffectsInRender","createSelector","serializeQueryArgs","context","usePossiblyImmediateEffect","cb","unsubscribePromiseRef","ref","endpointDefinitions","buildQueryHooks","buildInfiniteQueryHooks","buildMutationHook","usePrefetch","queryStatePreSelector","currentState","lastResult","queryArgs","endpointName","endpointDefinition","skipToken","data","hasData","isFetching","isLoading","isSuccess","infiniteQueryStatePreSelector","defaultOptions","dispatch","stableDefaultOptions","useShallowStableValue","useCallback","arg","options","useQuerySubscriptionCommonImpl","refetchOnReconnect","refetchOnFocus","refetchOnMountOrArgChange","skip","pollingInterval","skipPollingIfUnfocused","rest","initiate","subscriptionSelectorsRef","useRef","returnedValue","stableArg","useStableQueryArgs","stableSubscriptionOptions","initialPageParam","stableInitialPageParam","refetchCachedPages","stableRefetchCachedPages","promiseRef","queryCacheKey","requestId","currentRenderHasSubscription","subscriptionRemoved","lastPromise","lastSubscriptionOptions","promise","isInfiniteQueryDefinition","buildUseQueryState","preSelector","selectFromResult","select","lastValue","selectDefaultResult","useMemo","_","shallowEqual","querySelector","state","store","newLastValue","usePromiseRefUnsubscribeOnUnmount","refetchOrErrorIfUnmounted","_formatProdErrorMessage2","useQuerySubscription","useLazyQuerySubscription","setArg","useState","UNINITIALIZED_VALUE","subscriptionOptionsRef","trigger","preferCacheValue","reset","useQueryState","queryStateResults","info","querySubscriptionResults","debugValue","useDebugValue","useInfiniteQuerySubscription","hookRefetchCachedPages","stableHookRefetchCachedPages","direction","refetch","_formatProdErrorMessage3","mergedOptions","useInfiniteQueryState","fetchNextPage","fetchPreviousPage","name","fixedCacheKey","setPromise","triggerMutation","mutationSelector","originalArgs","finalState","reactHooksModuleName","reactHooksModule","batch","rrBatch","hooks","rrUseDispatch","rrUseSelector","rrUseStore","createSelector","_createSelector","unstable__sideEffectsInRender","rest","api","serializeQueryArgs","context","anyApi","buildQueryHooks","buildInfiniteQueryHooks","buildMutationHook","usePrefetch","buildHooks","safeAssign","endpointName","definition","isQueryDefinition","useQuery","useLazyQuery","useLazyQuerySubscription","useQueryState","useQuerySubscription","capitalize","isMutationDefinition","useMutation","isInfiniteQueryDefinition","useInfiniteQuery","useInfiniteQuerySubscription","useInfiniteQueryState","configureStore","_formatProdErrorMessage","React","ApiProvider","props","context","ReactReduxContext","useContext","_formatProdErrorMessage","store","configureStore","gDM","useEffect","setupListeners","Provider","createApi","buildCreateApi","coreModule","reactHooksModule"]}
Index: node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.legacy-esm.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,740 @@
+var __defProp = Object.defineProperty;
+var __defProps = Object.defineProperties;
+var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
+var __getOwnPropSymbols = Object.getOwnPropertySymbols;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __propIsEnum = Object.prototype.propertyIsEnumerable;
+var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __spreadValues = (a, b) => {
+  for (var prop in b || (b = {}))
+    if (__hasOwnProp.call(b, prop))
+      __defNormalProp(a, prop, b[prop]);
+  if (__getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(b)) {
+      if (__propIsEnum.call(b, prop))
+        __defNormalProp(a, prop, b[prop]);
+    }
+  return a;
+};
+var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
+var __objRest = (source, exclude) => {
+  var target = {};
+  for (var prop in source)
+    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
+      target[prop] = source[prop];
+  if (source != null && __getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(source)) {
+      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
+        target[prop] = source[prop];
+    }
+  return target;
+};
+
+// src/query/react/rtkqImports.ts
+import { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from "@reduxjs/toolkit/query";
+
+// src/query/react/module.ts
+import { formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
+import { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from "react-redux";
+import { createSelector as _createSelector } from "reselect";
+
+// src/query/utils/capitalize.ts
+function capitalize(str) {
+  return str.replace(str[0], str[0].toUpperCase());
+}
+
+// src/query/utils/countObjectKeys.ts
+function countObjectKeys(obj) {
+  let count = 0;
+  for (const _key in obj) {
+    count++;
+  }
+  return count;
+}
+
+// src/query/endpointDefinitions.ts
+var ENDPOINT_QUERY = "query" /* query */;
+var ENDPOINT_MUTATION = "mutation" /* mutation */;
+var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
+function isQueryDefinition(e) {
+  return e.type === ENDPOINT_QUERY;
+}
+function isMutationDefinition(e) {
+  return e.type === ENDPOINT_MUTATION;
+}
+function isInfiniteQueryDefinition(e) {
+  return e.type === ENDPOINT_INFINITEQUERY;
+}
+
+// src/query/tsHelpers.ts
+function safeAssign(target, ...args) {
+  return Object.assign(target, ...args);
+}
+
+// src/query/react/buildHooks.ts
+import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
+
+// src/query/react/reactImports.ts
+import { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from "react";
+
+// src/query/react/reactReduxImports.ts
+import { shallowEqual, Provider, ReactReduxContext } from "react-redux";
+
+// src/query/react/constants.ts
+var UNINITIALIZED_VALUE = Symbol();
+
+// src/query/react/useSerializedStableValue.ts
+function useStableQueryArgs(queryArgs) {
+  const cache = useRef(queryArgs);
+  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);
+  useEffect(() => {
+    if (cache.current !== copy) {
+      cache.current = copy;
+    }
+  }, [copy]);
+  return copy;
+}
+
+// src/query/react/useShallowStableValue.ts
+function useShallowStableValue(value) {
+  const cache = useRef(value);
+  useEffect(() => {
+    if (!shallowEqual(cache.current, value)) {
+      cache.current = value;
+    }
+  }, [value]);
+  return shallowEqual(cache.current, value) ? cache.current : value;
+}
+
+// src/query/react/buildHooks.ts
+var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
+var isDOM = /* @__PURE__ */ canUseDOM();
+var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
+var isReactNative = /* @__PURE__ */ isRunningInReactNative();
+var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;
+var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
+var noPendingQueryStateSelector = (selected) => {
+  if (selected.isUninitialized) {
+    return __spreadProps(__spreadValues({}, selected), {
+      isUninitialized: false,
+      isFetching: true,
+      isLoading: selected.data !== void 0 ? 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
+    });
+  }
+  return selected;
+};
+function pick(obj, ...keys) {
+  const ret = {};
+  keys.forEach((key) => {
+    ret[key] = obj[key];
+  });
+  return ret;
+}
+var COMMON_HOOK_DEBUG_FIELDS = ["data", "status", "isLoading", "isSuccess", "isError", "error"];
+function buildHooks({
+  api,
+  moduleOptions: {
+    batch,
+    hooks: {
+      useDispatch,
+      useSelector,
+      useStore
+    },
+    unstable__sideEffectsInRender,
+    createSelector
+  },
+  serializeQueryArgs,
+  context
+}) {
+  const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect;
+  const unsubscribePromiseRef = (ref) => {
+    var _a, _b;
+    return (_b = (_a = ref.current) == null ? void 0 : _a.unsubscribe) == null ? void 0 : _b.call(_a);
+  };
+  const endpointDefinitions = context.endpointDefinitions;
+  return {
+    buildQueryHooks,
+    buildInfiniteQueryHooks,
+    buildMutationHook,
+    usePrefetch
+  };
+  function queryStatePreSelector(currentState, lastResult, queryArgs) {
+    if ((lastResult == null ? void 0 : 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 = void 0;
+    }
+    let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
+    if (data === void 0) data = currentState.data;
+    const hasData = data !== void 0;
+    const isFetching = currentState.isLoading;
+    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
+    const isSuccess = currentState.isSuccess || hasData && (isFetching && !(lastResult == null ? void 0 : lastResult.isError) || currentState.isUninitialized);
+    return __spreadProps(__spreadValues({}, currentState), {
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess
+    });
+  }
+  function infiniteQueryStatePreSelector(currentState, lastResult, queryArgs) {
+    if ((lastResult == null ? void 0 : 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 = void 0;
+    }
+    let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
+    if (data === void 0) data = currentState.data;
+    const hasData = data !== void 0;
+    const isFetching = currentState.isLoading;
+    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
+    const isSuccess = currentState.isSuccess || isFetching && hasData;
+    return __spreadProps(__spreadValues({}, currentState), {
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess
+    });
+  }
+  function usePrefetch(endpointName, defaultOptions) {
+    const dispatch = useDispatch();
+    const stableDefaultOptions = useShallowStableValue(defaultOptions);
+    return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
+  }
+  function useQuerySubscriptionCommonImpl(endpointName, arg, _a = {}) {
+    var _b = _a, {
+      refetchOnReconnect,
+      refetchOnFocus,
+      refetchOnMountOrArgChange,
+      skip = false,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false
+    } = _b, rest = __objRest(_b, [
+      "refetchOnReconnect",
+      "refetchOnFocus",
+      "refetchOnMountOrArgChange",
+      "skip",
+      "pollingInterval",
+      "skipPollingIfUnfocused"
+    ]);
+    const {
+      initiate
+    } = api.endpoints[endpointName];
+    const dispatch = useDispatch();
+    const subscriptionSelectorsRef = useRef(void 0);
+    if (!subscriptionSelectorsRef.current) {
+      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
+      if (process.env.NODE_ENV !== "production") {
+        if (typeof returnedValue !== "object" || typeof (returnedValue == null ? void 0 : returnedValue.type) === "string") {
+          throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(37) : `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;
+    }
+    const stableArg = useStableQueryArgs(skip ? skipToken : arg);
+    const stableSubscriptionOptions = useShallowStableValue({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval,
+      skipPollingIfUnfocused
+    });
+    const initialPageParam = rest.initialPageParam;
+    const stableInitialPageParam = useShallowStableValue(initialPageParam);
+    const refetchCachedPages = rest.refetchCachedPages;
+    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);
+    const promiseRef = useRef(void 0);
+    let {
+      queryCacheKey,
+      requestId
+    } = promiseRef.current || {};
+    let currentRenderHasSubscription = false;
+    if (queryCacheKey && requestId) {
+      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
+    }
+    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== void 0;
+    usePossiblyImmediateEffect(() => {
+      if (subscriptionRemoved) {
+        promiseRef.current = void 0;
+      }
+    }, [subscriptionRemoved]);
+    usePossiblyImmediateEffect(() => {
+      var _a2;
+      const lastPromise = promiseRef.current;
+      if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
+        console.log(subscriptionRemoved);
+      }
+      if (stableArg === skipToken) {
+        lastPromise == null ? void 0 : lastPromise.unsubscribe();
+        promiseRef.current = void 0;
+        return;
+      }
+      const lastSubscriptionOptions = (_a2 = promiseRef.current) == null ? void 0 : _a2.subscriptionOptions;
+      if (!lastPromise || lastPromise.arg !== stableArg) {
+        lastPromise == null ? void 0 : lastPromise.unsubscribe();
+        const promise = dispatch(initiate(stableArg, __spreadValues({
+          subscriptionOptions: stableSubscriptionOptions,
+          forceRefetch: refetchOnMountOrArgChange
+        }, isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {
+          initialPageParam: stableInitialPageParam,
+          refetchCachedPages: stableRefetchCachedPages
+        } : {})));
+        promiseRef.current = promise;
+      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
+      }
+    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);
+    return [promiseRef, dispatch, initiate, stableSubscriptionOptions];
+  }
+  function buildUseQueryState(endpointName, preSelector) {
+    const useQueryState = (arg, {
+      skip = false,
+      selectFromResult
+    } = {}) => {
+      const {
+        select
+      } = api.endpoints[endpointName];
+      const stableArg = useStableQueryArgs(skip ? skipToken : arg);
+      const lastValue = useRef(void 0);
+      const selectDefaultResult = 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),
+          (_, lastResult) => lastResult,
+          (_) => stableArg
+        ], preSelector, {
+          memoizeOptions: {
+            resultEqualityCheck: shallowEqual
+          }
+        })
+      ), [select, stableArg]);
+      const querySelector = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {
+        devModeChecks: {
+          identityFunctionCheck: "never"
+        }
+      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
+      const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual);
+      const store = useStore();
+      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
+      useIsomorphicLayoutEffect(() => {
+        lastValue.current = newLastValue;
+      }, [newLastValue]);
+      return currentState;
+    };
+    return useQueryState;
+  }
+  function usePromiseRefUnsubscribeOnUnmount(promiseRef) {
+    useEffect(() => {
+      return () => {
+        unsubscribePromiseRef(promiseRef);
+        promiseRef.current = void 0;
+      };
+    }, [promiseRef]);
+  }
+  function refetchOrErrorIfUnmounted(promiseRef) {
+    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
+    return promiseRef.current.refetch();
+  }
+  function buildQueryHooks(endpointName) {
+    const useQuerySubscription = (arg, options = {}) => {
+      const [promiseRef] = useQuerySubscriptionCommonImpl(endpointName, arg, options);
+      usePromiseRefUnsubscribeOnUnmount(promiseRef);
+      return useMemo(() => ({
+        /**
+         * A method to manually refetch data for the query
+         */
+        refetch: () => refetchOrErrorIfUnmounted(promiseRef)
+      }), [promiseRef]);
+    };
+    const useLazyQuerySubscription = ({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false
+    } = {}) => {
+      const {
+        initiate
+      } = api.endpoints[endpointName];
+      const dispatch = useDispatch();
+      const [arg, setArg] = useState(UNINITIALIZED_VALUE);
+      const promiseRef = useRef(void 0);
+      const stableSubscriptionOptions = useShallowStableValue({
+        refetchOnReconnect,
+        refetchOnFocus,
+        pollingInterval,
+        skipPollingIfUnfocused
+      });
+      usePossiblyImmediateEffect(() => {
+        var _a, _b;
+        const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
+        if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+          (_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
+        }
+      }, [stableSubscriptionOptions]);
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions;
+      }, [stableSubscriptionOptions]);
+      const trigger = useCallback(function(arg2, preferCacheValue = false) {
+        let promise;
+        batch(() => {
+          unsubscribePromiseRef(promiseRef);
+          promiseRef.current = promise = dispatch(initiate(arg2, {
+            subscriptionOptions: subscriptionOptionsRef.current,
+            forceRefetch: !preferCacheValue
+          }));
+          setArg(arg2);
+        });
+        return promise;
+      }, [dispatch, initiate]);
+      const reset = useCallback(() => {
+        var _a, _b;
+        if ((_a = promiseRef.current) == null ? void 0 : _a.queryCacheKey) {
+          dispatch(api.internalActions.removeQueryResult({
+            queryCacheKey: (_b = promiseRef.current) == null ? void 0 : _b.queryCacheKey
+          }));
+        }
+      }, [dispatch]);
+      useEffect(() => {
+        return () => {
+          unsubscribePromiseRef(promiseRef);
+        };
+      }, []);
+      useEffect(() => {
+        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
+          trigger(arg, true);
+        }
+      }, [arg, trigger]);
+      return useMemo(() => [trigger, arg, {
+        reset
+      }], [trigger, arg, reset]);
+    };
+    const useQueryState = buildUseQueryState(endpointName, queryStatePreSelector);
+    return {
+      useQueryState,
+      useQuerySubscription,
+      useLazyQuerySubscription,
+      useLazyQuery(options) {
+        const [trigger, arg, {
+          reset
+        }] = useLazyQuerySubscription(options);
+        const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
+          skip: arg === UNINITIALIZED_VALUE
+        }));
+        const info = useMemo(() => ({
+          lastArg: arg
+        }), [arg]);
+        return useMemo(() => [trigger, __spreadProps(__spreadValues({}, queryStateResults), {
+          reset
+        }), info], [trigger, queryStateResults, reset, info]);
+      },
+      useQuery(arg, options) {
+        const querySubscriptionResults = useQuerySubscription(arg, options);
+        const queryStateResults = useQueryState(arg, __spreadValues({
+          selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
+        }, options));
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);
+        useDebugValue(debugValue);
+        return useMemo(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
+      }
+    };
+  }
+  function buildInfiniteQueryHooks(endpointName) {
+    const useInfiniteQuerySubscription = (arg, options = {}) => {
+      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl(endpointName, arg, options);
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions;
+      }, [stableSubscriptionOptions]);
+      const hookRefetchCachedPages = options.refetchCachedPages;
+      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);
+      const trigger = useCallback(function(arg2, direction) {
+        let promise;
+        batch(() => {
+          unsubscribePromiseRef(promiseRef);
+          promiseRef.current = promise = dispatch(initiate(arg2, {
+            subscriptionOptions: subscriptionOptionsRef.current,
+            direction
+          }));
+        });
+        return promise;
+      }, [promiseRef, dispatch, initiate]);
+      usePromiseRefUnsubscribeOnUnmount(promiseRef);
+      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);
+      const refetch = useCallback((options2) => {
+        var _a;
+        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(38) : "Cannot refetch a query that has not been started yet.");
+        const mergedOptions = {
+          refetchCachedPages: (_a = options2 == null ? void 0 : options2.refetchCachedPages) != null ? _a : 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 = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);
+    return {
+      useInfiniteQueryState,
+      useInfiniteQuerySubscription,
+      useInfiniteQuery(arg, options) {
+        const {
+          refetch,
+          fetchNextPage,
+          fetchPreviousPage
+        } = useInfiniteQuerySubscription(arg, options);
+        const queryStateResults = useInfiniteQueryState(arg, __spreadValues({
+          selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
+        }, options));
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, "hasNextPage", "hasPreviousPage");
+        useDebugValue(debugValue);
+        return useMemo(() => __spreadProps(__spreadValues({}, queryStateResults), {
+          fetchNextPage,
+          fetchPreviousPage,
+          refetch
+        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);
+      }
+    };
+  }
+  function buildMutationHook(name) {
+    return ({
+      selectFromResult,
+      fixedCacheKey
+    } = {}) => {
+      const {
+        select,
+        initiate
+      } = api.endpoints[name];
+      const dispatch = useDispatch();
+      const [promise, setPromise] = useState();
+      useEffect(() => () => {
+        if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
+          promise == null ? void 0 : promise.reset();
+        }
+      }, [promise]);
+      const triggerMutation = useCallback(function(arg) {
+        const promise2 = dispatch(initiate(arg, {
+          fixedCacheKey
+        }));
+        setPromise(promise2);
+        return promise2;
+      }, [dispatch, initiate, fixedCacheKey]);
+      const {
+        requestId
+      } = promise || {};
+      const selectDefaultResult = useMemo(() => select({
+        fixedCacheKey,
+        requestId: promise == null ? void 0 : promise.requestId
+      }), [fixedCacheKey, promise, select]);
+      const mutationSelector = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
+      const currentState = useSelector(mutationSelector, shallowEqual);
+      const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
+      const reset = useCallback(() => {
+        batch(() => {
+          if (promise) {
+            setPromise(void 0);
+          }
+          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(() => __spreadProps(__spreadValues({}, currentState), {
+        originalArgs,
+        reset
+      }), [currentState, originalArgs, reset]);
+      return useMemo(() => [triggerMutation, finalState], [triggerMutation, finalState]);
+    };
+  }
+}
+
+// src/query/react/module.ts
+var reactHooksModuleName = /* @__PURE__ */ Symbol();
+var reactHooksModule = (_a = {}) => {
+  var _b = _a, {
+    batch = rrBatch,
+    hooks = {
+      useDispatch: rrUseDispatch,
+      useSelector: rrUseSelector,
+      useStore: rrUseStore
+    },
+    createSelector = _createSelector,
+    unstable__sideEffectsInRender = false
+  } = _b, rest = __objRest(_b, [
+    "batch",
+    "hooks",
+    "createSelector",
+    "unstable__sideEffectsInRender"
+  ]);
+  if (process.env.NODE_ENV !== "production") {
+    const hookNames = ["useDispatch", "useSelector", "useStore"];
+    let warned = false;
+    for (const hookName of hookNames) {
+      if (countObjectKeys(rest) > 0) {
+        if (rest[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;
+          }
+        }
+        hooks[hookName] = rest[hookName];
+      }
+      if (typeof hooks[hookName] !== "function") {
+        throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
+Hook ${hookName} was either not provided or not a function.`);
+      }
+    }
+  }
+  return {
+    name: reactHooksModuleName,
+    init(api, {
+      serializeQueryArgs
+    }, context) {
+      const anyApi = api;
+      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[`use${capitalize(endpointName)}Query`] = useQuery;
+            api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
+          }
+          if (isMutationDefinition(definition)) {
+            const useMutation = buildMutationHook(endpointName);
+            safeAssign(anyApi.endpoints[endpointName], {
+              useMutation
+            });
+            api[`use${capitalize(endpointName)}Mutation`] = useMutation;
+          } else if (isInfiniteQueryDefinition(definition)) {
+            const {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState
+            } = buildInfiniteQueryHooks(endpointName);
+            safeAssign(anyApi.endpoints[endpointName], {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState
+            });
+            api[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;
+          }
+        }
+      };
+    }
+  };
+};
+
+// src/query/react/index.ts
+export * from "@reduxjs/toolkit/query";
+
+// src/query/react/ApiProvider.tsx
+import { configureStore, formatProdErrorMessage as _formatProdErrorMessage5 } from "@reduxjs/toolkit";
+import * as React from "react";
+function ApiProvider(props) {
+  const context = props.context || ReactReduxContext;
+  const existingContext = useContext(context);
+  if (existingContext) {
+    throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage5(35) : "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)
+  }));
+  useEffect(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
+  return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children);
+}
+
+// src/query/react/index.ts
+var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
+export {
+  ApiProvider,
+  UNINITIALIZED_VALUE,
+  createApi,
+  reactHooksModule,
+  reactHooksModuleName
+};
+//# sourceMappingURL=rtk-query-react.legacy-esm.js.map
Index: node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.legacy-esm.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/query/react/rtkqImports.ts","../../../src/query/react/module.ts","../../../src/query/utils/capitalize.ts","../../../src/query/utils/countObjectKeys.ts","../../../src/query/endpointDefinitions.ts","../../../src/query/tsHelpers.ts","../../../src/query/react/buildHooks.ts","../../../src/query/react/reactImports.ts","../../../src/query/react/reactReduxImports.ts","../../../src/query/react/constants.ts","../../../src/query/react/useSerializedStableValue.ts","../../../src/query/react/useShallowStableValue.ts","../../../src/query/react/index.ts","../../../src/query/react/ApiProvider.tsx"],"sourcesContent":["export { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from '@reduxjs/toolkit/query';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Api, BaseQueryFn, EndpointDefinitions, InfiniteQueryDefinition, Module, MutationDefinition, PrefetchOptions, QueryArgFrom, QueryDefinition, QueryKeys } from '@reduxjs/toolkit/query';\nimport { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from 'react-redux';\nimport type { CreateSelectorFunction } from 'reselect';\nimport { createSelector as _createSelector } from 'reselect';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { safeAssign } from '../tsHelpers';\nimport { capitalize, countObjectKeys } from '../utils';\nimport type { InfiniteQueryHooks, MutationHooks, QueryHooks } from './buildHooks';\nimport { buildHooks } from './buildHooks';\nimport type { HooksWithUniqueNames } from './namedHooks';\nexport const reactHooksModuleName = /* @__PURE__ */Symbol();\nexport type ReactHooksModule = typeof reactHooksModuleName;\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  ReducerPath extends string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  TagTypes extends string> {\n    [reactHooksModuleName]: {\n      /**\n       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n       */\n      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 };\n      /**\n       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n       */\n      usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;\n    } & HooksWithUniqueNames<Definitions>;\n  }\n}\ntype RR = typeof import('react-redux');\nexport interface ReactHooksModuleOptions {\n  /**\n   * The hooks from React Redux to be used\n   */\n  hooks?: {\n    /**\n     * The version of the `useDispatch` hook to be used\n     */\n    useDispatch: RR['useDispatch'];\n    /**\n     * The version of the `useSelector` hook to be used\n     */\n    useSelector: RR['useSelector'];\n    /**\n     * The version of the `useStore` hook to be used\n     */\n    useStore: RR['useStore'];\n  };\n  /**\n   * The version of the `batchedUpdates` function to be used\n   */\n  batch?: RR['batch'];\n  /**\n   * Enables performing asynchronous tasks immediately within a render.\n   *\n   * @example\n   *\n   * ```ts\n   * import {\n   *   buildCreateApi,\n   *   coreModule,\n   *   reactHooksModule\n   * } from '@reduxjs/toolkit/query/react'\n   *\n   * const createApi = buildCreateApi(\n   *   coreModule(),\n   *   reactHooksModule({ unstable__sideEffectsInRender: true })\n   * )\n   * ```\n   */\n  unstable__sideEffectsInRender?: boolean;\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n *  @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n  batch = rrBatch,\n  hooks = {\n    useDispatch: rrUseDispatch,\n    useSelector: rrUseSelector,\n    useStore: rrUseStore\n  },\n  createSelector = _createSelector,\n  unstable__sideEffectsInRender = false,\n  ...rest\n}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {\n  if (process.env.NODE_ENV !== 'production') {\n    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const;\n    let warned = false;\n    for (const hookName of hookNames) {\n      // warn for old hook options\n      if (countObjectKeys(rest) > 0) {\n        if ((rest as Partial<typeof hooks>)[hookName]) {\n          if (!warned) {\n            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 } })`');\n            warned = true;\n          }\n        }\n        // migrate\n        // @ts-ignore\n        hooks[hookName] = rest[hookName];\n      }\n      // then make sure we have them all\n      if (typeof hooks[hookName] !== 'function') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(36) : `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.`);\n      }\n    }\n  }\n  return {\n    name: reactHooksModuleName,\n    init(api, {\n      serializeQueryArgs\n    }, context) {\n      const anyApi = api as any as Api<any, Record<string, any>, any, any, ReactHooksModule>;\n      const {\n        buildQueryHooks,\n        buildInfiniteQueryHooks,\n        buildMutationHook,\n        usePrefetch\n      } = buildHooks({\n        api,\n        moduleOptions: {\n          batch,\n          hooks,\n          unstable__sideEffectsInRender,\n          createSelector\n        },\n        serializeQueryArgs,\n        context\n      });\n      safeAssign(anyApi, {\n        usePrefetch\n      });\n      safeAssign(context, {\n        batch\n      });\n      return {\n        injectEndpoint(endpointName, definition) {\n          if (isQueryDefinition(definition)) {\n            const {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            } = buildQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            });\n            (api as any)[`use${capitalize(endpointName)}Query`] = useQuery;\n            (api as any)[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;\n          }\n          if (isMutationDefinition(definition)) {\n            const useMutation = buildMutationHook(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useMutation\n            });\n            (api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation;\n          } else if (isInfiniteQueryDefinition(definition)) {\n            const {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            } = buildInfiniteQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            });\n            (api as any)[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;\n          }\n        }\n      };\n    }\n  };\n};","export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase());\n}","// Fast method for counting an object's keys\n// without resorting to `Object.keys(obj).length\n// Will this make a big difference in perf? Probably not\n// But we can save a few allocations.\n\nexport function countObjectKeys(obj: Record<any, any>) {\n  let count = 0;\n  for (const _key in obj) {\n    count++;\n  }\n  return count;\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Selector, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport 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';\nimport { QueryStatus, skipToken } from './rtkqImports';\nimport type { DependencyList } from 'react';\nimport { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/index';\nimport type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index';\nimport type { UninitializedValue } from './constants';\nimport { UNINITIALIZED_VALUE } from './constants';\nimport type { ReactHooksModuleOptions } from './module';\nimport { useStableQueryArgs } from './useSerializedStableValue';\nimport { useShallowStableValue } from './useShallowStableValue';\nimport type { InfiniteQueryDirection } from '../core/apiState';\nimport { isInfiniteQueryDefinition } from '../endpointDefinitions';\nimport type { StartInfiniteQueryActionCreator } from '../core/buildInitiate';\n\n// Copy-pasted from React-Redux\nconst canUseDOM = () => !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nconst isDOM = /* @__PURE__ */canUseDOM();\n\n// Under React Native, we know that we always want to use useLayoutEffect\n\nconst isRunningInReactNative = () => typeof navigator !== 'undefined' && navigator.product === 'ReactNative';\nconst isReactNative = /* @__PURE__ */isRunningInReactNative();\nconst getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;\nexport const useIsomorphicLayoutEffect = /* @__PURE__ */getUseIsomorphicLayoutEffect();\nexport type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  useQuery: UseQuery<Definition>;\n  useLazyQuery: UseLazyQuery<Definition>;\n  useQuerySubscription: UseQuerySubscription<Definition>;\n  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;\n  useQueryState: UseQueryState<Definition>;\n};\nexport type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  useInfiniteQuery: UseInfiniteQuery<Definition>;\n  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;\n  useInfiniteQueryState: UseInfiniteQueryState<Definition>;\n};\nexport type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  useMutation: UseMutation<Definition>;\n};\n\n/**\n * 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.\n *\n * 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.\n *\n * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuery` hook in userland code.\n */\nexport type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;\nexport type UseQuerySubscriptionOptions = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n};\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;\nexport type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {\n  lastArg: QueryArgFrom<D>;\n};\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - 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\n *\n * #### Note\n *\n * 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.\n */\nexport 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>];\nexport type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useLazyQuery` hook in userland code.\n */\nexport type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\nexport type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;\n};\nexport type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - 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\n */\nexport type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, {\n  reset: () => void;\n}];\nexport type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   title: string\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * type SelectedResult = Pick<PostsApiResponse, 'posts'>\n *\n * const postsApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, QueryArgument>({\n *       query: (limit = 5) => `?limit=${limit}&select=title`,\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = postsApiSlice\n *\n * function PostById({ id }: { id: number }) {\n *   const { post } = useGetPostsQuery(undefined, {\n *     selectFromResult: (state) => ({\n *       post: state.data?.posts.find((post) => post.id === id),\n *     }),\n *   })\n *\n *   return <li>{post?.title}</li>\n * }\n *\n * const EMPTY_ARRAY: Post[] = []\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n *\n * function PostsList() {\n *   const { posts } = useGetPostsQuery(undefined, {\n *     selectFromResult: typedSelectFromResult,\n *   })\n *\n *   return (\n *     <div>\n *       <ul>\n *         {posts.map((post) => (\n *           <PostById key={post.id} id={post.id} />\n *         ))}\n *       </ul>\n *     </div>\n *   )\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.3.0\n * @public\n */\nexport 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>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: QueryStateSelector<R, D>;\n};\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * <caption>#### __Create a `useQuery` hook with default options__</caption>\n *\n * ```ts\n * import type {\n *   SubscriptionOptions,\n *   TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   name: string\n * }\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   tagTypes: ['Post'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<Post[], void>({\n *       query: () => 'posts',\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = api\n *\n * export const useGetPostsQueryWithDefaults = <\n *   SelectedResult extends Record<string, any>,\n * >(\n *   overrideOptions: TypedUseQueryStateOptions<\n *     Post[],\n *     void,\n *     ReturnType<typeof fetchBaseQuery>,\n *     SelectedResult\n *   > &\n *     SubscriptionOptions,\n * ) =>\n *   useGetPostsQuery(undefined, {\n *     // Insert default options here\n *\n *     refetchOnMountOrArgChange: true,\n *     refetchOnFocus: true,\n *     ...overrideOptions,\n *   })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.2.8\n * @public\n */\nexport 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>;\nexport type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;\ntype UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: ResultTypeFrom<D>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n};\ntype UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}>;\ntype UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n}>;\ntype UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n  currentData: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isError: true;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;\ntype UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;\n};\nexport type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  initialPageParam?: PageParamFrom<D>;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   *\n   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).\n   * It can be overridden on a per-call basis using the `refetch()` method.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  refetch: (options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>) => InfiniteQueryActionCreatorResult<D>;\n  trigger: LazyInfiniteQueryTrigger<D>;\n  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;\nexport 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>>;\n\n/**\n * 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.\n *\n * 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.\n *\n *  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.\n *\n * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.\n *\n * 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.\n *\n * 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.\n *\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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'>;\nexport type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;\nexport type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;\nexport 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>;\nexport type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: InfiniteQueryStateSelector<R, D>;\n};\nexport 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>;\nexport type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;\nexport 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>;\ntype UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n};\ntype UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n} | ({\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({\n  isError: true;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;\nexport type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  selectFromResult?: MutationStateSelector<R, D>;\n  fixedCacheKey?: string;\n};\nexport type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {\n  originalArgs?: QueryArgFrom<D>;\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\n\n/**\n * 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.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>];\nexport type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {\n  /**\n   * Triggers the mutation and returns a Promise.\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;\n};\nexport type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector<any, any> = selected => {\n  if (selected.isUninitialized) {\n    return {\n      ...selected,\n      isUninitialized: false,\n      isFetching: true,\n      isLoading: selected.data !== undefined ? false : true,\n      // This is the one place where we still have to use `QueryStatus` as an enum,\n      // since it's the only reference in the React package and not in the core.\n      status: QueryStatus.pending\n    } as any;\n  }\n  return selected;\n};\nfunction pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {\n  const ret: any = {};\n  keys.forEach(key => {\n    ret[key] = obj[key];\n  });\n  return ret;\n}\nconst COMMON_HOOK_DEBUG_FIELDS = ['data', 'status', 'isLoading', 'isSuccess', 'isError', 'error'] as const;\ntype GenericPrefetchThunk = (endpointName: any, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, UnknownAction>;\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks<Definitions extends EndpointDefinitions>({\n  api,\n  moduleOptions: {\n    batch,\n    hooks: {\n      useDispatch,\n      useSelector,\n      useStore\n    },\n    unstable__sideEffectsInRender,\n    createSelector\n  },\n  serializeQueryArgs,\n  context\n}: {\n  api: Api<any, Definitions, any, any, CoreModule>;\n  moduleOptions: Required<ReactHooksModuleOptions>;\n  serializeQueryArgs: SerializeQueryArgs<any>;\n  context: ApiContext<Definitions>;\n}) {\n  const usePossiblyImmediateEffect: (effect: () => void | undefined, deps?: DependencyList) => void = unstable__sideEffectsInRender ? cb => cb() : useEffect;\n  type UnsubscribePromiseRef = React.RefObject<{\n    unsubscribe?: () => void;\n  } | undefined>;\n  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) => ref.current?.unsubscribe?.();\n  const endpointDefinitions = context.endpointDefinitions;\n  return {\n    buildQueryHooks,\n    buildInfiniteQueryHooks,\n    buildMutationHook,\n    usePrefetch\n  };\n  function queryStatePreSelector(currentState: QueryResultSelectorResult<any>, lastResult: UseQueryStateDefaultResult<any> | undefined, queryArgs: any): UseQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n\n    // isSuccess = true when data is present and we're not refetching after an error.\n    // That includes cases where the _current_ item is either actively\n    // fetching or about to fetch due to an uninitialized entry.\n    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseQueryStateDefaultResult<any>;\n  }\n  function infiniteQueryStatePreSelector(currentState: InfiniteQueryResultSelectorResult<any>, lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined, queryArgs: any): UseInfiniteQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n    // isSuccess = true when data is present\n    const isSuccess = currentState.isSuccess || isFetching && hasData;\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseInfiniteQueryStateDefaultResult<any>;\n  }\n  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions) {\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n    const stableDefaultOptions = useShallowStableValue(defaultOptions);\n    return useCallback((arg: any, options?: PrefetchOptions) => dispatch((api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n      ...stableDefaultOptions,\n      ...options\n    })), [endpointName, dispatch, stableDefaultOptions]);\n  }\n  function useQuerySubscriptionCommonImpl<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(endpointName: string, arg: unknown | SkipToken, {\n    refetchOnReconnect,\n    refetchOnFocus,\n    refetchOnMountOrArgChange,\n    skip = false,\n    pollingInterval = 0,\n    skipPollingIfUnfocused = false,\n    ...rest\n  }: UseQuerySubscriptionOptions = {}) {\n    const {\n      initiate\n    } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n\n    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.\n    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(undefined);\n    if (!subscriptionSelectorsRef.current) {\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n    You must add the middleware for RTK-Query to function correctly!`);\n        }\n      }\n      subscriptionSelectorsRef.current = returnedValue as unknown as SubscriptionSelectors;\n    }\n    const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n    const stableSubscriptionOptions = useShallowStableValue({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval,\n      skipPollingIfUnfocused\n    });\n    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>).initialPageParam;\n    const stableInitialPageParam = useShallowStableValue(initialPageParam);\n    const refetchCachedPages = (rest as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);\n\n    /**\n     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n     */\n    const promiseRef = useRef<T | undefined>(undefined);\n    let {\n      queryCacheKey,\n      requestId\n    } = promiseRef.current || {};\n\n    // HACK We've saved the middleware subscription lookup callbacks into a ref,\n    // so we can directly check here if the subscription exists for this query.\n    let currentRenderHasSubscription = false;\n    if (queryCacheKey && requestId) {\n      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);\n    }\n    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== undefined;\n    usePossiblyImmediateEffect((): void | undefined => {\n      if (subscriptionRemoved) {\n        promiseRef.current = undefined;\n      }\n    }, [subscriptionRemoved]);\n    usePossiblyImmediateEffect((): void | undefined => {\n      const lastPromise = promiseRef.current;\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {\n        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n        console.log(subscriptionRemoved);\n      }\n      if (stableArg === skipToken) {\n        lastPromise?.unsubscribe();\n        promiseRef.current = undefined;\n        return;\n      }\n      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n      if (!lastPromise || lastPromise.arg !== stableArg) {\n        lastPromise?.unsubscribe();\n        const promise = dispatch(initiate(stableArg, {\n          subscriptionOptions: stableSubscriptionOptions,\n          forceRefetch: refetchOnMountOrArgChange,\n          ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {\n            initialPageParam: stableInitialPageParam,\n            refetchCachedPages: stableRefetchCachedPages\n          } : {})\n        }));\n        promiseRef.current = promise as T;\n      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\n      }\n    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);\n    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const;\n  }\n  function buildUseQueryState(endpointName: string, preSelector: typeof queryStatePreSelector | typeof infiniteQueryStatePreSelector) {\n    const useQueryState = (arg: any, {\n      skip = false,\n      selectFromResult\n    }: UseQueryStateOptions<any, any> | UseInfiniteQueryStateOptions<any, any> = {}) => {\n      const {\n        select\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n      type ApiRootState = Parameters<ReturnType<typeof select>>[0];\n      const lastValue = useRef<any>(undefined);\n      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(() =>\n      // Normally ts-ignores are bad and should be avoided, but we're\n      // already casting this selector to be `Selector<any>` anyway,\n      // so the inconsistencies don't matter here\n      // @ts-ignore\n      createSelector([\n      // @ts-ignore\n      select(stableArg), (_: ApiRootState, lastResult: any) => lastResult, (_: ApiRootState) => stableArg], preSelector, {\n        memoizeOptions: {\n          resultEqualityCheck: shallowEqual\n        }\n      }), [select, stableArg]);\n      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {\n        devModeChecks: {\n          identityFunctionCheck: 'never'\n        }\n      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);\n      const currentState = useSelector((state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current), shallowEqual);\n      const store = useStore<RootState<Definitions, any, any>>();\n      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);\n      useIsomorphicLayoutEffect(() => {\n        lastValue.current = newLastValue;\n      }, [newLastValue]);\n      return currentState;\n    };\n    return useQueryState;\n  }\n  function usePromiseRefUnsubscribeOnUnmount(promiseRef: UnsubscribePromiseRef) {\n    useEffect(() => {\n      return () => {\n        unsubscribePromiseRef(promiseRef)\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        ;\n        (promiseRef.current as any) = undefined;\n      };\n    }, [promiseRef]);\n  }\n  function refetchOrErrorIfUnmounted<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(promiseRef: React.RefObject<T | undefined>): T {\n    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(38) : 'Cannot refetch a query that has not been started yet.');\n    return promiseRef.current.refetch() as T;\n  }\n  function buildQueryHooks(endpointName: string): QueryHooks<any> {\n    const useQuerySubscription: UseQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef] = useQuerySubscriptionCommonImpl<QueryActionCreatorResult<any>>(endpointName, arg, options);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      return useMemo(() => ({\n        /**\n         * A method to manually refetch data for the query\n         */\n        refetch: () => refetchOrErrorIfUnmounted(promiseRef)\n      }), [promiseRef]);\n    };\n    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false\n    } = {}) => {\n      const {\n        initiate\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE);\n\n      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n      /**\n       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n       */\n      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(undefined);\n      const stableSubscriptionOptions = useShallowStableValue({\n        refetchOnReconnect,\n        refetchOnFocus,\n        pollingInterval,\n        skipPollingIfUnfocused\n      });\n      usePossiblyImmediateEffect(() => {\n        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n        if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n          promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);\n        }\n      }, [stableSubscriptionOptions]);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n      const trigger = useCallback(function (arg: any, preferCacheValue = false) {\n        let promise: QueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch(initiate(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            forceRefetch: !preferCacheValue\n          }));\n          setArg(arg);\n        });\n        return promise!;\n      }, [dispatch, initiate]);\n      const reset = useCallback(() => {\n        if (promiseRef.current?.queryCacheKey) {\n          dispatch(api.internalActions.removeQueryResult({\n            queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey\n          }));\n        }\n      }, [dispatch]);\n\n      /* cleanup on unmount */\n      useEffect(() => {\n        return () => {\n          unsubscribePromiseRef(promiseRef);\n        };\n      }, []);\n\n      /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n      useEffect(() => {\n        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n          trigger(arg, true);\n        }\n      }, [arg, trigger]);\n      return useMemo(() => [trigger, arg, {\n        reset\n      }] as const, [trigger, arg, reset]);\n    };\n    const useQueryState: UseQueryState<any> = buildUseQueryState(endpointName, queryStatePreSelector);\n    return {\n      useQueryState,\n      useQuerySubscription,\n      useLazyQuerySubscription,\n      useLazyQuery(options) {\n        const [trigger, arg, {\n          reset\n        }] = useLazyQuerySubscription(options);\n        const queryStateResults = useQueryState(arg, {\n          ...options,\n          skip: arg === UNINITIALIZED_VALUE\n        });\n        const info = useMemo(() => ({\n          lastArg: arg\n        }), [arg]);\n        return useMemo(() => [trigger, {\n          ...queryStateResults,\n          reset\n        }, info], [trigger, queryStateResults, reset, info]);\n      },\n      useQuery(arg, options) {\n        const querySubscriptionResults = useQuerySubscription(arg, options);\n        const queryStateResults = useQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          ...querySubscriptionResults\n        }), [queryStateResults, querySubscriptionResults]);\n      }\n    };\n  }\n  function buildInfiniteQueryHooks(endpointName: string): InfiniteQueryHooks<any> {\n    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(endpointName, arg, options);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n\n      // Extract and stabilize the hook-level refetchCachedPages option\n      const hookRefetchCachedPages = (options as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);\n      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(function (arg: unknown, direction: 'forward' | 'backward') {\n        let promise: InfiniteQueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch((initiate as StartInfiniteQueryActionCreator<any>)(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            direction\n          }));\n        });\n        return promise!;\n      }, [promiseRef, dispatch, initiate]);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);\n      const refetch = useCallback((options?: Pick<UseInfiniteQuerySubscriptionOptions<any>, 'refetchCachedPages'>) => {\n        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(38) : 'Cannot refetch a query that has not been started yet.');\n        // Merge per-call options with hook-level default\n        const mergedOptions = {\n          refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages\n        };\n        return promiseRef.current.refetch(mergedOptions);\n      }, [promiseRef, stableHookRefetchCachedPages]);\n      return useMemo(() => {\n        const fetchNextPage = () => {\n          return trigger(stableArg, 'forward');\n        };\n        const fetchPreviousPage = () => {\n          return trigger(stableArg, 'backward');\n        };\n        return {\n          trigger,\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        };\n      }, [refetch, trigger, stableArg]);\n    };\n    const useInfiniteQueryState: UseInfiniteQueryState<any> = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);\n    return {\n      useInfiniteQueryState,\n      useInfiniteQuerySubscription,\n      useInfiniteQuery(arg, options) {\n        const {\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        } = useInfiniteQuerySubscription(arg, options);\n        const queryStateResults = useInfiniteQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, 'hasNextPage', 'hasPreviousPage');\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          fetchNextPage,\n          fetchPreviousPage,\n          refetch\n        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);\n      }\n    };\n  }\n  function buildMutationHook(name: string): UseMutation<any> {\n    return ({\n      selectFromResult,\n      fixedCacheKey\n    } = {}) => {\n      const {\n        select,\n        initiate\n      } = api.endpoints[name] as ApiEndpointMutation<MutationDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>();\n      useEffect(() => () => {\n        if (!promise?.arg.fixedCacheKey) {\n          promise?.reset();\n        }\n      }, [promise]);\n      const triggerMutation = useCallback(function (arg: Parameters<typeof initiate>['0']) {\n        const promise = dispatch(initiate(arg, {\n          fixedCacheKey\n        }));\n        setPromise(promise);\n        return promise;\n      }, [dispatch, initiate, fixedCacheKey]);\n      const {\n        requestId\n      } = promise || {};\n      const selectDefaultResult = useMemo(() => select({\n        fixedCacheKey,\n        requestId: promise?.requestId\n      }), [fixedCacheKey, promise, select]);\n      const mutationSelector = useMemo((): Selector<RootState<Definitions, any, any>, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);\n      const currentState = useSelector(mutationSelector, shallowEqual);\n      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;\n      const reset = useCallback(() => {\n        batch(() => {\n          if (promise) {\n            setPromise(undefined);\n          }\n          if (fixedCacheKey) {\n            dispatch(api.internalActions.removeMutationResult({\n              requestId,\n              fixedCacheKey\n            }));\n          }\n        });\n      }, [dispatch, fixedCacheKey, promise, requestId]);\n      const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, 'endpointName');\n      useDebugValue(debugValue);\n      const finalState = useMemo(() => ({\n        ...currentState,\n        originalArgs,\n        reset\n      }), [currentState, originalArgs, reset]);\n      return useMemo(() => [triggerMutation, finalState] as const, [triggerMutation, finalState]);\n    };\n  }\n}","export { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from 'react';","export { shallowEqual, Provider, ReactReduxContext } from 'react-redux';","export const UNINITIALIZED_VALUE = Symbol();\nexport type UninitializedValue = typeof UNINITIALIZED_VALUE;","import { useEffect, useRef, useMemo } from './reactImports';\nimport { copyWithStructuralSharing } from './rtkqImports';\nexport function useStableQueryArgs<T>(queryArgs: T) {\n  const cache = useRef(queryArgs);\n  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);\n  useEffect(() => {\n    if (cache.current !== copy) {\n      cache.current = copy;\n    }\n  }, [copy]);\n  return copy;\n}","import { useEffect, useRef } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nexport function useShallowStableValue<T>(value: T) {\n  const cache = useRef(value);\n  useEffect(() => {\n    if (!shallowEqual(cache.current, value)) {\n      cache.current = value;\n    }\n  }, [value]);\n  return shallowEqual(cache.current, value) ? cache.current : value;\n}","// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nimport { buildCreateApi, coreModule } from './rtkqImports';\nimport { reactHooksModule, reactHooksModuleName } from './module';\nexport * from '@reduxjs/toolkit/query';\nexport { ApiProvider } from './ApiProvider';\nconst createApi = /* @__PURE__ */buildCreateApi(coreModule(), reactHooksModule());\nexport 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';\nexport { UNINITIALIZED_VALUE } from './constants';\nexport { createApi, reactHooksModule, reactHooksModuleName };","import { configureStore, formatProdErrorMessage as _formatProdErrorMessage } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport { useContext, useEffect } from './reactImports';\nimport * as React from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { Provider, ReactReduxContext } from './reactReduxImports';\nimport { setupListeners } from './rtkqImports';\nimport type { Api } from '@reduxjs/toolkit/query';\n\n/**\n * Can be used as a `Provider` if you **do not already have a Redux store**.\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Basic usage - wrap your App with ApiProvider\"\n * import * as React from 'react';\n * import { ApiProvider } from '@reduxjs/toolkit/query/react';\n * import { Pokemon } from './features/Pokemon';\n *\n * function App() {\n *   return (\n *     <ApiProvider api={api}>\n *       <Pokemon />\n *     </ApiProvider>\n *   );\n * }\n * ```\n *\n * @remarks\n * Using this together with an existing redux store, both will\n * conflict with each other - please use the traditional redux setup\n * in that case.\n */\nexport function ApiProvider(props: {\n  children: any;\n  api: Api<any, {}, any, any>;\n  setupListeners?: Parameters<typeof setupListeners>[1] | false;\n  context?: Context<ReactReduxContextValue | null>;\n}) {\n  const context = props.context || ReactReduxContext;\n  const existingContext = useContext(context);\n  if (existingContext) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(35) : 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.');\n  }\n  const [store] = React.useState(() => configureStore({\n    reducer: {\n      [props.api.reducerPath]: props.api.reducer\n    },\n    middleware: gDM => gDM().concat(props.api.middleware)\n  }));\n  // Adds the event listeners for online/offline/focus/etc\n  useEffect((): undefined | (() => void) => props.setupListeners === false ? undefined : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);\n  return <Provider store={store} context={context}>\n      {props.children}\n    </Provider>;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB,YAAY,2BAA2B,gBAAgB,aAAa,iBAAiB;;;ACA9G,SAAS,0BAA0BA,gCAA+B;AAElE,SAAS,SAAS,SAAS,eAAe,eAAe,eAAe,eAAe,YAAY,kBAAkB;AAErH,SAAS,kBAAkB,uBAAuB;;;ACJ3C,SAAS,WAAW,KAAa;AACtC,SAAO,IAAI,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,EAAE,YAAY,CAAC;AACjD;;;ACGO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,QAAQ;AACZ,aAAW,QAAQ,KAAK;AACtB;AAAA,EACF;AACA,SAAO;AACT;;;AC8XO,IAA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AAAA,EACtM;AACA,QAAM,CAAC,KAAK,IAAU,eAAS,MAAM,eAAe;AAAA,IAClD,SAAS;AAAA,MACP,CAAC,MAAM,IAAI,WAAW,GAAG,MAAM,IAAI;AAAA,IACrC;AAAA,IACA,YAAY,SAAO,IAAI,EAAE,OAAO,MAAM,IAAI,UAAU;AAAA,EACtD,CAAC,CAAC;AAEF,YAAU,MAAgC,MAAM,mBAAmB,QAAQ,SAAY,eAAe,MAAM,UAAU,MAAM,cAAc,GAAG,CAAC,MAAM,gBAAgB,MAAM,QAAQ,CAAC;AACnL,SAAO,oCAAC,YAAS,OAAc,WAC1B,MAAM,QACT;AACJ;;;ADhDA,IAAM,YAA2B,+BAAe,WAAW,GAAG,iBAAiB,CAAC;","names":["_formatProdErrorMessage","_a","arg","options","promise","_formatProdErrorMessage","_formatProdErrorMessage","_formatProdErrorMessage"]}
Index: node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.modern.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,705 @@
+// src/query/react/rtkqImports.ts
+import { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from "@reduxjs/toolkit/query";
+
+// src/query/react/module.ts
+import { formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
+import { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from "react-redux";
+import { createSelector as _createSelector } from "reselect";
+
+// src/query/utils/capitalize.ts
+function capitalize(str) {
+  return str.replace(str[0], str[0].toUpperCase());
+}
+
+// src/query/utils/countObjectKeys.ts
+function countObjectKeys(obj) {
+  let count = 0;
+  for (const _key in obj) {
+    count++;
+  }
+  return count;
+}
+
+// src/query/endpointDefinitions.ts
+var ENDPOINT_QUERY = "query" /* query */;
+var ENDPOINT_MUTATION = "mutation" /* mutation */;
+var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
+function isQueryDefinition(e) {
+  return e.type === ENDPOINT_QUERY;
+}
+function isMutationDefinition(e) {
+  return e.type === ENDPOINT_MUTATION;
+}
+function isInfiniteQueryDefinition(e) {
+  return e.type === ENDPOINT_INFINITEQUERY;
+}
+
+// src/query/tsHelpers.ts
+function safeAssign(target, ...args) {
+  return Object.assign(target, ...args);
+}
+
+// src/query/react/buildHooks.ts
+import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
+
+// src/query/react/reactImports.ts
+import { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from "react";
+
+// src/query/react/reactReduxImports.ts
+import { shallowEqual, Provider, ReactReduxContext } from "react-redux";
+
+// src/query/react/constants.ts
+var UNINITIALIZED_VALUE = Symbol();
+
+// src/query/react/useSerializedStableValue.ts
+function useStableQueryArgs(queryArgs) {
+  const cache = useRef(queryArgs);
+  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);
+  useEffect(() => {
+    if (cache.current !== copy) {
+      cache.current = copy;
+    }
+  }, [copy]);
+  return copy;
+}
+
+// src/query/react/useShallowStableValue.ts
+function useShallowStableValue(value) {
+  const cache = useRef(value);
+  useEffect(() => {
+    if (!shallowEqual(cache.current, value)) {
+      cache.current = value;
+    }
+  }, [value]);
+  return shallowEqual(cache.current, value) ? cache.current : value;
+}
+
+// src/query/react/buildHooks.ts
+var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
+var isDOM = /* @__PURE__ */ canUseDOM();
+var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
+var isReactNative = /* @__PURE__ */ isRunningInReactNative();
+var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;
+var useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
+var noPendingQueryStateSelector = (selected) => {
+  if (selected.isUninitialized) {
+    return {
+      ...selected,
+      isUninitialized: false,
+      isFetching: true,
+      isLoading: selected.data !== void 0 ? 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
+    };
+  }
+  return selected;
+};
+function pick(obj, ...keys) {
+  const ret = {};
+  keys.forEach((key) => {
+    ret[key] = obj[key];
+  });
+  return ret;
+}
+var COMMON_HOOK_DEBUG_FIELDS = ["data", "status", "isLoading", "isSuccess", "isError", "error"];
+function buildHooks({
+  api,
+  moduleOptions: {
+    batch,
+    hooks: {
+      useDispatch,
+      useSelector,
+      useStore
+    },
+    unstable__sideEffectsInRender,
+    createSelector
+  },
+  serializeQueryArgs,
+  context
+}) {
+  const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect;
+  const unsubscribePromiseRef = (ref) => ref.current?.unsubscribe?.();
+  const endpointDefinitions = context.endpointDefinitions;
+  return {
+    buildQueryHooks,
+    buildInfiniteQueryHooks,
+    buildMutationHook,
+    usePrefetch
+  };
+  function queryStatePreSelector(currentState, lastResult, queryArgs) {
+    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 = void 0;
+    }
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data;
+    if (data === void 0) data = currentState.data;
+    const hasData = data !== void 0;
+    const isFetching = currentState.isLoading;
+    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
+    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess
+    };
+  }
+  function infiniteQueryStatePreSelector(currentState, lastResult, queryArgs) {
+    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 = void 0;
+    }
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data;
+    if (data === void 0) data = currentState.data;
+    const hasData = data !== void 0;
+    const isFetching = currentState.isLoading;
+    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
+    const isSuccess = currentState.isSuccess || isFetching && hasData;
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess
+    };
+  }
+  function usePrefetch(endpointName, defaultOptions) {
+    const dispatch = useDispatch();
+    const stableDefaultOptions = useShallowStableValue(defaultOptions);
+    return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, {
+      ...stableDefaultOptions,
+      ...options
+    })), [endpointName, dispatch, stableDefaultOptions]);
+  }
+  function useQuerySubscriptionCommonImpl(endpointName, arg, {
+    refetchOnReconnect,
+    refetchOnFocus,
+    refetchOnMountOrArgChange,
+    skip = false,
+    pollingInterval = 0,
+    skipPollingIfUnfocused = false,
+    ...rest
+  } = {}) {
+    const {
+      initiate
+    } = api.endpoints[endpointName];
+    const dispatch = useDispatch();
+    const subscriptionSelectorsRef = useRef(void 0);
+    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(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(37) : `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;
+    }
+    const stableArg = useStableQueryArgs(skip ? skipToken : arg);
+    const stableSubscriptionOptions = useShallowStableValue({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval,
+      skipPollingIfUnfocused
+    });
+    const initialPageParam = rest.initialPageParam;
+    const stableInitialPageParam = useShallowStableValue(initialPageParam);
+    const refetchCachedPages = rest.refetchCachedPages;
+    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);
+    const promiseRef = useRef(void 0);
+    let {
+      queryCacheKey,
+      requestId
+    } = promiseRef.current || {};
+    let currentRenderHasSubscription = false;
+    if (queryCacheKey && requestId) {
+      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);
+    }
+    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== void 0;
+    usePossiblyImmediateEffect(() => {
+      if (subscriptionRemoved) {
+        promiseRef.current = void 0;
+      }
+    }, [subscriptionRemoved]);
+    usePossiblyImmediateEffect(() => {
+      const lastPromise = promiseRef.current;
+      if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
+        console.log(subscriptionRemoved);
+      }
+      if (stableArg === skipToken) {
+        lastPromise?.unsubscribe();
+        promiseRef.current = void 0;
+        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;
+      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
+      }
+    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);
+    return [promiseRef, dispatch, initiate, stableSubscriptionOptions];
+  }
+  function buildUseQueryState(endpointName, preSelector) {
+    const useQueryState = (arg, {
+      skip = false,
+      selectFromResult
+    } = {}) => {
+      const {
+        select
+      } = api.endpoints[endpointName];
+      const stableArg = useStableQueryArgs(skip ? skipToken : arg);
+      const lastValue = useRef(void 0);
+      const selectDefaultResult = 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),
+          (_, lastResult) => lastResult,
+          (_) => stableArg
+        ], preSelector, {
+          memoizeOptions: {
+            resultEqualityCheck: shallowEqual
+          }
+        })
+      ), [select, stableArg]);
+      const querySelector = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {
+        devModeChecks: {
+          identityFunctionCheck: "never"
+        }
+      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
+      const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual);
+      const store = useStore();
+      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
+      useIsomorphicLayoutEffect(() => {
+        lastValue.current = newLastValue;
+      }, [newLastValue]);
+      return currentState;
+    };
+    return useQueryState;
+  }
+  function usePromiseRefUnsubscribeOnUnmount(promiseRef) {
+    useEffect(() => {
+      return () => {
+        unsubscribePromiseRef(promiseRef);
+        promiseRef.current = void 0;
+      };
+    }, [promiseRef]);
+  }
+  function refetchOrErrorIfUnmounted(promiseRef) {
+    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(38) : "Cannot refetch a query that has not been started yet.");
+    return promiseRef.current.refetch();
+  }
+  function buildQueryHooks(endpointName) {
+    const useQuerySubscription = (arg, options = {}) => {
+      const [promiseRef] = useQuerySubscriptionCommonImpl(endpointName, arg, options);
+      usePromiseRefUnsubscribeOnUnmount(promiseRef);
+      return useMemo(() => ({
+        /**
+         * A method to manually refetch data for the query
+         */
+        refetch: () => refetchOrErrorIfUnmounted(promiseRef)
+      }), [promiseRef]);
+    };
+    const useLazyQuerySubscription = ({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false
+    } = {}) => {
+      const {
+        initiate
+      } = api.endpoints[endpointName];
+      const dispatch = useDispatch();
+      const [arg, setArg] = useState(UNINITIALIZED_VALUE);
+      const promiseRef = useRef(void 0);
+      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(arg2, preferCacheValue = false) {
+        let promise;
+        batch(() => {
+          unsubscribePromiseRef(promiseRef);
+          promiseRef.current = promise = dispatch(initiate(arg2, {
+            subscriptionOptions: subscriptionOptionsRef.current,
+            forceRefetch: !preferCacheValue
+          }));
+          setArg(arg2);
+        });
+        return promise;
+      }, [dispatch, initiate]);
+      const reset = useCallback(() => {
+        if (promiseRef.current?.queryCacheKey) {
+          dispatch(api.internalActions.removeQueryResult({
+            queryCacheKey: promiseRef.current?.queryCacheKey
+          }));
+        }
+      }, [dispatch]);
+      useEffect(() => {
+        return () => {
+          unsubscribePromiseRef(promiseRef);
+        };
+      }, []);
+      useEffect(() => {
+        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
+          trigger(arg, true);
+        }
+      }, [arg, trigger]);
+      return useMemo(() => [trigger, arg, {
+        reset
+      }], [trigger, arg, reset]);
+    };
+    const useQueryState = 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 ? void 0 : noPendingQueryStateSelector,
+          ...options
+        });
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);
+        useDebugValue(debugValue);
+        return useMemo(() => ({
+          ...queryStateResults,
+          ...querySubscriptionResults
+        }), [queryStateResults, querySubscriptionResults]);
+      }
+    };
+  }
+  function buildInfiniteQueryHooks(endpointName) {
+    const useInfiniteQuerySubscription = (arg, options = {}) => {
+      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl(endpointName, arg, options);
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions;
+      }, [stableSubscriptionOptions]);
+      const hookRefetchCachedPages = options.refetchCachedPages;
+      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);
+      const trigger = useCallback(function(arg2, direction) {
+        let promise;
+        batch(() => {
+          unsubscribePromiseRef(promiseRef);
+          promiseRef.current = promise = dispatch(initiate(arg2, {
+            subscriptionOptions: subscriptionOptionsRef.current,
+            direction
+          }));
+        });
+        return promise;
+      }, [promiseRef, dispatch, initiate]);
+      usePromiseRefUnsubscribeOnUnmount(promiseRef);
+      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);
+      const refetch = useCallback((options2) => {
+        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(38) : "Cannot refetch a query that has not been started yet.");
+        const mergedOptions = {
+          refetchCachedPages: options2?.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 = 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 ? void 0 : 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) {
+    return ({
+      selectFromResult,
+      fixedCacheKey
+    } = {}) => {
+      const {
+        select,
+        initiate
+      } = api.endpoints[name];
+      const dispatch = useDispatch();
+      const [promise, setPromise] = useState();
+      useEffect(() => () => {
+        if (!promise?.arg.fixedCacheKey) {
+          promise?.reset();
+        }
+      }, [promise]);
+      const triggerMutation = useCallback(function(arg) {
+        const promise2 = dispatch(initiate(arg, {
+          fixedCacheKey
+        }));
+        setPromise(promise2);
+        return promise2;
+      }, [dispatch, initiate, fixedCacheKey]);
+      const {
+        requestId
+      } = promise || {};
+      const selectDefaultResult = useMemo(() => select({
+        fixedCacheKey,
+        requestId: promise?.requestId
+      }), [fixedCacheKey, promise, select]);
+      const mutationSelector = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);
+      const currentState = useSelector(mutationSelector, shallowEqual);
+      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : void 0;
+      const reset = useCallback(() => {
+        batch(() => {
+          if (promise) {
+            setPromise(void 0);
+          }
+          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], [triggerMutation, finalState]);
+    };
+  }
+}
+
+// src/query/react/module.ts
+var reactHooksModuleName = /* @__PURE__ */ Symbol();
+var reactHooksModule = ({
+  batch = rrBatch,
+  hooks = {
+    useDispatch: rrUseDispatch,
+    useSelector: rrUseSelector,
+    useStore: rrUseStore
+  },
+  createSelector = _createSelector,
+  unstable__sideEffectsInRender = false,
+  ...rest
+} = {}) => {
+  if (process.env.NODE_ENV !== "production") {
+    const hookNames = ["useDispatch", "useSelector", "useStore"];
+    let warned = false;
+    for (const hookName of hookNames) {
+      if (countObjectKeys(rest) > 0) {
+        if (rest[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;
+          }
+        }
+        hooks[hookName] = rest[hookName];
+      }
+      if (typeof hooks[hookName] !== "function") {
+        throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(36) : `When using custom hooks for context, all ${hookNames.length} hooks need to be provided: ${hookNames.join(", ")}.
+Hook ${hookName} was either not provided or not a function.`);
+      }
+    }
+  }
+  return {
+    name: reactHooksModuleName,
+    init(api, {
+      serializeQueryArgs
+    }, context) {
+      const anyApi = api;
+      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[`use${capitalize(endpointName)}Query`] = useQuery;
+            api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
+          }
+          if (isMutationDefinition(definition)) {
+            const useMutation = buildMutationHook(endpointName);
+            safeAssign(anyApi.endpoints[endpointName], {
+              useMutation
+            });
+            api[`use${capitalize(endpointName)}Mutation`] = useMutation;
+          } else if (isInfiniteQueryDefinition(definition)) {
+            const {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState
+            } = buildInfiniteQueryHooks(endpointName);
+            safeAssign(anyApi.endpoints[endpointName], {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState
+            });
+            api[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;
+          }
+        }
+      };
+    }
+  };
+};
+
+// src/query/react/index.ts
+export * from "@reduxjs/toolkit/query";
+
+// src/query/react/ApiProvider.tsx
+import { configureStore, formatProdErrorMessage as _formatProdErrorMessage5 } from "@reduxjs/toolkit";
+import * as React from "react";
+function ApiProvider(props) {
+  const context = props.context || ReactReduxContext;
+  const existingContext = useContext(context);
+  if (existingContext) {
+    throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage5(35) : "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)
+  }));
+  useEffect(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
+  return /* @__PURE__ */ React.createElement(Provider, { store, context }, props.children);
+}
+
+// src/query/react/index.ts
+var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
+export {
+  ApiProvider,
+  UNINITIALIZED_VALUE,
+  createApi,
+  reactHooksModule,
+  reactHooksModuleName
+};
+//# sourceMappingURL=rtk-query-react.modern.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.modern.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/react/rtk-query-react.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/query/react/rtkqImports.ts","../../../src/query/react/module.ts","../../../src/query/utils/capitalize.ts","../../../src/query/utils/countObjectKeys.ts","../../../src/query/endpointDefinitions.ts","../../../src/query/tsHelpers.ts","../../../src/query/react/buildHooks.ts","../../../src/query/react/reactImports.ts","../../../src/query/react/reactReduxImports.ts","../../../src/query/react/constants.ts","../../../src/query/react/useSerializedStableValue.ts","../../../src/query/react/useShallowStableValue.ts","../../../src/query/react/index.ts","../../../src/query/react/ApiProvider.tsx"],"sourcesContent":["export { buildCreateApi, coreModule, copyWithStructuralSharing, setupListeners, QueryStatus, skipToken } from '@reduxjs/toolkit/query';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Api, BaseQueryFn, EndpointDefinitions, InfiniteQueryDefinition, Module, MutationDefinition, PrefetchOptions, QueryArgFrom, QueryDefinition, QueryKeys } from '@reduxjs/toolkit/query';\nimport { batch as rrBatch, useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore } from 'react-redux';\nimport type { CreateSelectorFunction } from 'reselect';\nimport { createSelector as _createSelector } from 'reselect';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { safeAssign } from '../tsHelpers';\nimport { capitalize, countObjectKeys } from '../utils';\nimport type { InfiniteQueryHooks, MutationHooks, QueryHooks } from './buildHooks';\nimport { buildHooks } from './buildHooks';\nimport type { HooksWithUniqueNames } from './namedHooks';\nexport const reactHooksModuleName = /* @__PURE__ */Symbol();\nexport type ReactHooksModule = typeof reactHooksModuleName;\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  ReducerPath extends string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  TagTypes extends string> {\n    [reactHooksModuleName]: {\n      /**\n       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n       */\n      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 };\n      /**\n       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n       */\n      usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;\n    } & HooksWithUniqueNames<Definitions>;\n  }\n}\ntype RR = typeof import('react-redux');\nexport interface ReactHooksModuleOptions {\n  /**\n   * The hooks from React Redux to be used\n   */\n  hooks?: {\n    /**\n     * The version of the `useDispatch` hook to be used\n     */\n    useDispatch: RR['useDispatch'];\n    /**\n     * The version of the `useSelector` hook to be used\n     */\n    useSelector: RR['useSelector'];\n    /**\n     * The version of the `useStore` hook to be used\n     */\n    useStore: RR['useStore'];\n  };\n  /**\n   * The version of the `batchedUpdates` function to be used\n   */\n  batch?: RR['batch'];\n  /**\n   * Enables performing asynchronous tasks immediately within a render.\n   *\n   * @example\n   *\n   * ```ts\n   * import {\n   *   buildCreateApi,\n   *   coreModule,\n   *   reactHooksModule\n   * } from '@reduxjs/toolkit/query/react'\n   *\n   * const createApi = buildCreateApi(\n   *   coreModule(),\n   *   reactHooksModule({ unstable__sideEffectsInRender: true })\n   * )\n   * ```\n   */\n  unstable__sideEffectsInRender?: boolean;\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n *  @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n  batch = rrBatch,\n  hooks = {\n    useDispatch: rrUseDispatch,\n    useSelector: rrUseSelector,\n    useStore: rrUseStore\n  },\n  createSelector = _createSelector,\n  unstable__sideEffectsInRender = false,\n  ...rest\n}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {\n  if (process.env.NODE_ENV !== 'production') {\n    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const;\n    let warned = false;\n    for (const hookName of hookNames) {\n      // warn for old hook options\n      if (countObjectKeys(rest) > 0) {\n        if ((rest as Partial<typeof hooks>)[hookName]) {\n          if (!warned) {\n            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 } })`');\n            warned = true;\n          }\n        }\n        // migrate\n        // @ts-ignore\n        hooks[hookName] = rest[hookName];\n      }\n      // then make sure we have them all\n      if (typeof hooks[hookName] !== 'function') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(36) : `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.`);\n      }\n    }\n  }\n  return {\n    name: reactHooksModuleName,\n    init(api, {\n      serializeQueryArgs\n    }, context) {\n      const anyApi = api as any as Api<any, Record<string, any>, any, any, ReactHooksModule>;\n      const {\n        buildQueryHooks,\n        buildInfiniteQueryHooks,\n        buildMutationHook,\n        usePrefetch\n      } = buildHooks({\n        api,\n        moduleOptions: {\n          batch,\n          hooks,\n          unstable__sideEffectsInRender,\n          createSelector\n        },\n        serializeQueryArgs,\n        context\n      });\n      safeAssign(anyApi, {\n        usePrefetch\n      });\n      safeAssign(context, {\n        batch\n      });\n      return {\n        injectEndpoint(endpointName, definition) {\n          if (isQueryDefinition(definition)) {\n            const {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            } = buildQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription\n            });\n            (api as any)[`use${capitalize(endpointName)}Query`] = useQuery;\n            (api as any)[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;\n          }\n          if (isMutationDefinition(definition)) {\n            const useMutation = buildMutationHook(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useMutation\n            });\n            (api as any)[`use${capitalize(endpointName)}Mutation`] = useMutation;\n          } else if (isInfiniteQueryDefinition(definition)) {\n            const {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            } = buildInfiniteQueryHooks(endpointName);\n            safeAssign(anyApi.endpoints[endpointName], {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState\n            });\n            (api as any)[`use${capitalize(endpointName)}InfiniteQuery`] = useInfiniteQuery;\n          }\n        }\n      };\n    }\n  };\n};","export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase());\n}","// Fast method for counting an object's keys\n// without resorting to `Object.keys(obj).length\n// Will this make a big difference in perf? Probably not\n// But we can save a few allocations.\n\nexport function countObjectKeys(obj: Record<any, any>) {\n  let count = 0;\n  for (const _key in obj) {\n    count++;\n  }\n  return count;\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Selector, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport 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';\nimport { QueryStatus, skipToken } from './rtkqImports';\nimport type { DependencyList } from 'react';\nimport { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/index';\nimport type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index';\nimport type { UninitializedValue } from './constants';\nimport { UNINITIALIZED_VALUE } from './constants';\nimport type { ReactHooksModuleOptions } from './module';\nimport { useStableQueryArgs } from './useSerializedStableValue';\nimport { useShallowStableValue } from './useShallowStableValue';\nimport type { InfiniteQueryDirection } from '../core/apiState';\nimport { isInfiniteQueryDefinition } from '../endpointDefinitions';\nimport type { StartInfiniteQueryActionCreator } from '../core/buildInitiate';\n\n// Copy-pasted from React-Redux\nconst canUseDOM = () => !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nconst isDOM = /* @__PURE__ */canUseDOM();\n\n// Under React Native, we know that we always want to use useLayoutEffect\n\nconst isRunningInReactNative = () => typeof navigator !== 'undefined' && navigator.product === 'ReactNative';\nconst isReactNative = /* @__PURE__ */isRunningInReactNative();\nconst getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? useLayoutEffect : useEffect;\nexport const useIsomorphicLayoutEffect = /* @__PURE__ */getUseIsomorphicLayoutEffect();\nexport type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  useQuery: UseQuery<Definition>;\n  useLazyQuery: UseLazyQuery<Definition>;\n  useQuerySubscription: UseQuerySubscription<Definition>;\n  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;\n  useQueryState: UseQueryState<Definition>;\n};\nexport type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  useInfiniteQuery: UseInfiniteQuery<Definition>;\n  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;\n  useInfiniteQueryState: UseInfiniteQueryState<Definition>;\n};\nexport type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  useMutation: UseMutation<Definition>;\n};\n\n/**\n * 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.\n *\n * 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.\n *\n * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuery` hook in userland code.\n */\nexport type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;\nexport type UseQuerySubscriptionOptions = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n};\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;\nexport type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {\n  lastArg: QueryArgFrom<D>;\n};\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - 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\n *\n * #### Note\n *\n * 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.\n */\nexport 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>];\nexport type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useLazyQuery` hook in userland code.\n */\nexport type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\nexport type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;\n};\nexport type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - 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\n */\nexport type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, {\n  reset: () => void;\n}];\nexport type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   title: string\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * type SelectedResult = Pick<PostsApiResponse, 'posts'>\n *\n * const postsApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, QueryArgument>({\n *       query: (limit = 5) => `?limit=${limit}&select=title`,\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = postsApiSlice\n *\n * function PostById({ id }: { id: number }) {\n *   const { post } = useGetPostsQuery(undefined, {\n *     selectFromResult: (state) => ({\n *       post: state.data?.posts.find((post) => post.id === id),\n *     }),\n *   })\n *\n *   return <li>{post?.title}</li>\n * }\n *\n * const EMPTY_ARRAY: Post[] = []\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n *\n * function PostsList() {\n *   const { posts } = useGetPostsQuery(undefined, {\n *     selectFromResult: typedSelectFromResult,\n *   })\n *\n *   return (\n *     <div>\n *       <ul>\n *         {posts.map((post) => (\n *           <PostById key={post.id} id={post.id} />\n *         ))}\n *       </ul>\n *     </div>\n *   )\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.3.0\n * @public\n */\nexport 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>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: QueryStateSelector<R, D>;\n};\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * <caption>#### __Create a `useQuery` hook with default options__</caption>\n *\n * ```ts\n * import type {\n *   SubscriptionOptions,\n *   TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n *\n * type Post = {\n *   id: number\n *   name: string\n * }\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   tagTypes: ['Post'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<Post[], void>({\n *       query: () => 'posts',\n *     }),\n *   }),\n * })\n *\n * const { useGetPostsQuery } = api\n *\n * export const useGetPostsQueryWithDefaults = <\n *   SelectedResult extends Record<string, any>,\n * >(\n *   overrideOptions: TypedUseQueryStateOptions<\n *     Post[],\n *     void,\n *     ReturnType<typeof fetchBaseQuery>,\n *     SelectedResult\n *   > &\n *     SubscriptionOptions,\n * ) =>\n *   useGetPostsQuery(undefined, {\n *     // Insert default options here\n *\n *     refetchOnMountOrArgChange: true,\n *     refetchOnFocus: true,\n *     ...overrideOptions,\n *   })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.2.8\n * @public\n */\nexport 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>;\nexport type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;\ntype UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: ResultTypeFrom<D>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n};\ntype UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}>;\ntype UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n}>;\ntype UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & {\n  data: ResultTypeFrom<D>;\n  currentData: ResultTypeFrom<D>;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;\ntype UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {\n  isError: true;\n} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;\ntype UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * 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`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;\n};\nexport type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  initialPageParam?: PageParamFrom<D>;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   *\n   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).\n   * It can be overridden on a per-call basis using the `refetch()` method.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  refetch: (options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>) => InfiniteQueryActionCreatorResult<D>;\n  trigger: LazyInfiniteQueryTrigger<D>;\n  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\nexport type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;\nexport 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>>;\n\n/**\n * 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.\n *\n * 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.\n *\n *  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.\n *\n * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.\n *\n * 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.\n *\n * 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.\n *\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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'>;\nexport type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>;\nexport type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;\n\n/**\n * 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.\n *\n * 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.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;\nexport type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;\nexport 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>;\nexport type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * 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\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean;\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: InfiniteQueryStateSelector<R, D>;\n};\nexport 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>;\nexport type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;\nexport 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>;\ntype UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false;\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false;\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false;\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false;\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false;\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n};\ntype UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {\n  status: QueryStatus.uninitialized;\n}>, {\n  isUninitialized: true;\n}> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {\n  isLoading: true;\n  isFetching: boolean;\n  data: undefined;\n} | ({\n  isSuccess: true;\n  isFetching: true;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({\n  isSuccess: true;\n  isFetching: false;\n  error: undefined;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({\n  isError: true;\n} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus;\n};\nexport type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;\nexport type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {\n  selectFromResult?: MutationStateSelector<R, D>;\n  fixedCacheKey?: string;\n};\nexport type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {\n  originalArgs?: QueryArgFrom<D>;\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void;\n};\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;\n\n/**\n * 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.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport 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>];\nexport type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\nexport type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {\n  /**\n   * Triggers the mutation and returns a Promise.\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;\n};\nexport type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector<any, any> = selected => {\n  if (selected.isUninitialized) {\n    return {\n      ...selected,\n      isUninitialized: false,\n      isFetching: true,\n      isLoading: selected.data !== undefined ? false : true,\n      // This is the one place where we still have to use `QueryStatus` as an enum,\n      // since it's the only reference in the React package and not in the core.\n      status: QueryStatus.pending\n    } as any;\n  }\n  return selected;\n};\nfunction pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {\n  const ret: any = {};\n  keys.forEach(key => {\n    ret[key] = obj[key];\n  });\n  return ret;\n}\nconst COMMON_HOOK_DEBUG_FIELDS = ['data', 'status', 'isLoading', 'isSuccess', 'isError', 'error'] as const;\ntype GenericPrefetchThunk = (endpointName: any, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, UnknownAction>;\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks<Definitions extends EndpointDefinitions>({\n  api,\n  moduleOptions: {\n    batch,\n    hooks: {\n      useDispatch,\n      useSelector,\n      useStore\n    },\n    unstable__sideEffectsInRender,\n    createSelector\n  },\n  serializeQueryArgs,\n  context\n}: {\n  api: Api<any, Definitions, any, any, CoreModule>;\n  moduleOptions: Required<ReactHooksModuleOptions>;\n  serializeQueryArgs: SerializeQueryArgs<any>;\n  context: ApiContext<Definitions>;\n}) {\n  const usePossiblyImmediateEffect: (effect: () => void | undefined, deps?: DependencyList) => void = unstable__sideEffectsInRender ? cb => cb() : useEffect;\n  type UnsubscribePromiseRef = React.RefObject<{\n    unsubscribe?: () => void;\n  } | undefined>;\n  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) => ref.current?.unsubscribe?.();\n  const endpointDefinitions = context.endpointDefinitions;\n  return {\n    buildQueryHooks,\n    buildInfiniteQueryHooks,\n    buildMutationHook,\n    usePrefetch\n  };\n  function queryStatePreSelector(currentState: QueryResultSelectorResult<any>, lastResult: UseQueryStateDefaultResult<any> | undefined, queryArgs: any): UseQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n\n    // isSuccess = true when data is present and we're not refetching after an error.\n    // That includes cases where the _current_ item is either actively\n    // fetching or about to fetch due to an uninitialized entry.\n    const isSuccess = currentState.isSuccess || hasData && (isFetching && !lastResult?.isError || currentState.isUninitialized);\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseQueryStateDefaultResult<any>;\n  }\n  function infiniteQueryStatePreSelector(currentState: InfiniteQueryResultSelectorResult<any>, lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined, queryArgs: any): UseInfiniteQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const {\n        endpointName\n      } = lastResult;\n      const endpointDefinition = endpointDefinitions[endpointName];\n      if (queryArgs !== skipToken && serializeQueryArgs({\n        queryArgs: lastResult.originalArgs,\n        endpointDefinition,\n        endpointName\n      }) === serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      })) lastResult = undefined;\n    }\n\n    // 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\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data;\n    if (data === undefined) data = currentState.data;\n    const hasData = data !== undefined;\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading;\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;\n    // isSuccess = true when data is present\n    const isSuccess = currentState.isSuccess || isFetching && hasData;\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess\n    } as UseInfiniteQueryStateDefaultResult<any>;\n  }\n  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions) {\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n    const stableDefaultOptions = useShallowStableValue(defaultOptions);\n    return useCallback((arg: any, options?: PrefetchOptions) => dispatch((api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n      ...stableDefaultOptions,\n      ...options\n    })), [endpointName, dispatch, stableDefaultOptions]);\n  }\n  function useQuerySubscriptionCommonImpl<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(endpointName: string, arg: unknown | SkipToken, {\n    refetchOnReconnect,\n    refetchOnFocus,\n    refetchOnMountOrArgChange,\n    skip = false,\n    pollingInterval = 0,\n    skipPollingIfUnfocused = false,\n    ...rest\n  }: UseQuerySubscriptionOptions = {}) {\n    const {\n      initiate\n    } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n\n    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.\n    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(undefined);\n    if (!subscriptionSelectorsRef.current) {\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(37) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n    You must add the middleware for RTK-Query to function correctly!`);\n        }\n      }\n      subscriptionSelectorsRef.current = returnedValue as unknown as SubscriptionSelectors;\n    }\n    const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n    const stableSubscriptionOptions = useShallowStableValue({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval,\n      skipPollingIfUnfocused\n    });\n    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>).initialPageParam;\n    const stableInitialPageParam = useShallowStableValue(initialPageParam);\n    const refetchCachedPages = (rest as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);\n\n    /**\n     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n     */\n    const promiseRef = useRef<T | undefined>(undefined);\n    let {\n      queryCacheKey,\n      requestId\n    } = promiseRef.current || {};\n\n    // HACK We've saved the middleware subscription lookup callbacks into a ref,\n    // so we can directly check here if the subscription exists for this query.\n    let currentRenderHasSubscription = false;\n    if (queryCacheKey && requestId) {\n      currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(queryCacheKey, requestId);\n    }\n    const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== undefined;\n    usePossiblyImmediateEffect((): void | undefined => {\n      if (subscriptionRemoved) {\n        promiseRef.current = undefined;\n      }\n    }, [subscriptionRemoved]);\n    usePossiblyImmediateEffect((): void | undefined => {\n      const lastPromise = promiseRef.current;\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {\n        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n        console.log(subscriptionRemoved);\n      }\n      if (stableArg === skipToken) {\n        lastPromise?.unsubscribe();\n        promiseRef.current = undefined;\n        return;\n      }\n      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n      if (!lastPromise || lastPromise.arg !== stableArg) {\n        lastPromise?.unsubscribe();\n        const promise = dispatch(initiate(stableArg, {\n          subscriptionOptions: stableSubscriptionOptions,\n          forceRefetch: refetchOnMountOrArgChange,\n          ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {\n            initialPageParam: stableInitialPageParam,\n            refetchCachedPages: stableRefetchCachedPages\n          } : {})\n        }));\n        promiseRef.current = promise as T;\n      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\n      }\n    }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);\n    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const;\n  }\n  function buildUseQueryState(endpointName: string, preSelector: typeof queryStatePreSelector | typeof infiniteQueryStatePreSelector) {\n    const useQueryState = (arg: any, {\n      skip = false,\n      selectFromResult\n    }: UseQueryStateOptions<any, any> | UseInfiniteQueryStateOptions<any, any> = {}) => {\n      const {\n        select\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const stableArg = useStableQueryArgs(skip ? skipToken : arg);\n      type ApiRootState = Parameters<ReturnType<typeof select>>[0];\n      const lastValue = useRef<any>(undefined);\n      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(() =>\n      // Normally ts-ignores are bad and should be avoided, but we're\n      // already casting this selector to be `Selector<any>` anyway,\n      // so the inconsistencies don't matter here\n      // @ts-ignore\n      createSelector([\n      // @ts-ignore\n      select(stableArg), (_: ApiRootState, lastResult: any) => lastResult, (_: ApiRootState) => stableArg], preSelector, {\n        memoizeOptions: {\n          resultEqualityCheck: shallowEqual\n        }\n      }), [select, stableArg]);\n      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult, {\n        devModeChecks: {\n          identityFunctionCheck: 'never'\n        }\n      }) : selectDefaultResult, [selectDefaultResult, selectFromResult]);\n      const currentState = useSelector((state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current), shallowEqual);\n      const store = useStore<RootState<Definitions, any, any>>();\n      const newLastValue = selectDefaultResult(store.getState(), lastValue.current);\n      useIsomorphicLayoutEffect(() => {\n        lastValue.current = newLastValue;\n      }, [newLastValue]);\n      return currentState;\n    };\n    return useQueryState;\n  }\n  function usePromiseRefUnsubscribeOnUnmount(promiseRef: UnsubscribePromiseRef) {\n    useEffect(() => {\n      return () => {\n        unsubscribePromiseRef(promiseRef)\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        ;\n        (promiseRef.current as any) = undefined;\n      };\n    }, [promiseRef]);\n  }\n  function refetchOrErrorIfUnmounted<T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>(promiseRef: React.RefObject<T | undefined>): T {\n    if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(38) : 'Cannot refetch a query that has not been started yet.');\n    return promiseRef.current.refetch() as T;\n  }\n  function buildQueryHooks(endpointName: string): QueryHooks<any> {\n    const useQuerySubscription: UseQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef] = useQuerySubscriptionCommonImpl<QueryActionCreatorResult<any>>(endpointName, arg, options);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      return useMemo(() => ({\n        /**\n         * A method to manually refetch data for the query\n         */\n        refetch: () => refetchOrErrorIfUnmounted(promiseRef)\n      }), [promiseRef]);\n    };\n    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false\n    } = {}) => {\n      const {\n        initiate\n      } = api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE);\n\n      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n      /**\n       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n       */\n      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(undefined);\n      const stableSubscriptionOptions = useShallowStableValue({\n        refetchOnReconnect,\n        refetchOnFocus,\n        pollingInterval,\n        skipPollingIfUnfocused\n      });\n      usePossiblyImmediateEffect(() => {\n        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;\n        if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n          promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);\n        }\n      }, [stableSubscriptionOptions]);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n      const trigger = useCallback(function (arg: any, preferCacheValue = false) {\n        let promise: QueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch(initiate(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            forceRefetch: !preferCacheValue\n          }));\n          setArg(arg);\n        });\n        return promise!;\n      }, [dispatch, initiate]);\n      const reset = useCallback(() => {\n        if (promiseRef.current?.queryCacheKey) {\n          dispatch(api.internalActions.removeQueryResult({\n            queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey\n          }));\n        }\n      }, [dispatch]);\n\n      /* cleanup on unmount */\n      useEffect(() => {\n        return () => {\n          unsubscribePromiseRef(promiseRef);\n        };\n      }, []);\n\n      /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n      useEffect(() => {\n        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n          trigger(arg, true);\n        }\n      }, [arg, trigger]);\n      return useMemo(() => [trigger, arg, {\n        reset\n      }] as const, [trigger, arg, reset]);\n    };\n    const useQueryState: UseQueryState<any> = buildUseQueryState(endpointName, queryStatePreSelector);\n    return {\n      useQueryState,\n      useQuerySubscription,\n      useLazyQuerySubscription,\n      useLazyQuery(options) {\n        const [trigger, arg, {\n          reset\n        }] = useLazyQuerySubscription(options);\n        const queryStateResults = useQueryState(arg, {\n          ...options,\n          skip: arg === UNINITIALIZED_VALUE\n        });\n        const info = useMemo(() => ({\n          lastArg: arg\n        }), [arg]);\n        return useMemo(() => [trigger, {\n          ...queryStateResults,\n          reset\n        }, info], [trigger, queryStateResults, reset, info]);\n      },\n      useQuery(arg, options) {\n        const querySubscriptionResults = useQuerySubscription(arg, options);\n        const queryStateResults = useQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          ...querySubscriptionResults\n        }), [queryStateResults, querySubscriptionResults]);\n      }\n    };\n  }\n  function buildInfiniteQueryHooks(endpointName: string): InfiniteQueryHooks<any> {\n    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (arg: any, options = {}) => {\n      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] = useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(endpointName, arg, options);\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions);\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions;\n      }, [stableSubscriptionOptions]);\n\n      // Extract and stabilize the hook-level refetchCachedPages option\n      const hookRefetchCachedPages = (options as UseInfiniteQuerySubscriptionOptions<any>).refetchCachedPages;\n      const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);\n      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(function (arg: unknown, direction: 'forward' | 'backward') {\n        let promise: InfiniteQueryActionCreatorResult<any>;\n        batch(() => {\n          unsubscribePromiseRef(promiseRef);\n          promiseRef.current = promise = dispatch((initiate as StartInfiniteQueryActionCreator<any>)(arg, {\n            subscriptionOptions: subscriptionOptionsRef.current,\n            direction\n          }));\n        });\n        return promise!;\n      }, [promiseRef, dispatch, initiate]);\n      usePromiseRefUnsubscribeOnUnmount(promiseRef);\n      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);\n      const refetch = useCallback((options?: Pick<UseInfiniteQuerySubscriptionOptions<any>, 'refetchCachedPages'>) => {\n        if (!promiseRef.current) throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(38) : 'Cannot refetch a query that has not been started yet.');\n        // Merge per-call options with hook-level default\n        const mergedOptions = {\n          refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages\n        };\n        return promiseRef.current.refetch(mergedOptions);\n      }, [promiseRef, stableHookRefetchCachedPages]);\n      return useMemo(() => {\n        const fetchNextPage = () => {\n          return trigger(stableArg, 'forward');\n        };\n        const fetchPreviousPage = () => {\n          return trigger(stableArg, 'backward');\n        };\n        return {\n          trigger,\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        };\n      }, [refetch, trigger, stableArg]);\n    };\n    const useInfiniteQueryState: UseInfiniteQueryState<any> = buildUseQueryState(endpointName, infiniteQueryStatePreSelector);\n    return {\n      useInfiniteQueryState,\n      useInfiniteQuerySubscription,\n      useInfiniteQuery(arg, options) {\n        const {\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage\n        } = useInfiniteQuerySubscription(arg, options);\n        const queryStateResults = useInfiniteQueryState(arg, {\n          selectFromResult: arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,\n          ...options\n        });\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS, 'hasNextPage', 'hasPreviousPage');\n        useDebugValue(debugValue);\n        return useMemo(() => ({\n          ...queryStateResults,\n          fetchNextPage,\n          fetchPreviousPage,\n          refetch\n        }), [queryStateResults, fetchNextPage, fetchPreviousPage, refetch]);\n      }\n    };\n  }\n  function buildMutationHook(name: string): UseMutation<any> {\n    return ({\n      selectFromResult,\n      fixedCacheKey\n    } = {}) => {\n      const {\n        select,\n        initiate\n      } = api.endpoints[name] as ApiEndpointMutation<MutationDefinition<any, any, any, any, any>, Definitions>;\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>();\n      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>();\n      useEffect(() => () => {\n        if (!promise?.arg.fixedCacheKey) {\n          promise?.reset();\n        }\n      }, [promise]);\n      const triggerMutation = useCallback(function (arg: Parameters<typeof initiate>['0']) {\n        const promise = dispatch(initiate(arg, {\n          fixedCacheKey\n        }));\n        setPromise(promise);\n        return promise;\n      }, [dispatch, initiate, fixedCacheKey]);\n      const {\n        requestId\n      } = promise || {};\n      const selectDefaultResult = useMemo(() => select({\n        fixedCacheKey,\n        requestId: promise?.requestId\n      }), [fixedCacheKey, promise, select]);\n      const mutationSelector = useMemo((): Selector<RootState<Definitions, any, any>, any> => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectFromResult, selectDefaultResult]);\n      const currentState = useSelector(mutationSelector, shallowEqual);\n      const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;\n      const reset = useCallback(() => {\n        batch(() => {\n          if (promise) {\n            setPromise(undefined);\n          }\n          if (fixedCacheKey) {\n            dispatch(api.internalActions.removeMutationResult({\n              requestId,\n              fixedCacheKey\n            }));\n          }\n        });\n      }, [dispatch, fixedCacheKey, promise, requestId]);\n      const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, 'endpointName');\n      useDebugValue(debugValue);\n      const finalState = useMemo(() => ({\n        ...currentState,\n        originalArgs,\n        reset\n      }), [currentState, originalArgs, reset]);\n      return useMemo(() => [triggerMutation, finalState] as const, [triggerMutation, finalState]);\n    };\n  }\n}","export { useEffect, useRef, useMemo, useContext, useCallback, useDebugValue, useLayoutEffect, useState } from 'react';","export { shallowEqual, Provider, ReactReduxContext } from 'react-redux';","export const UNINITIALIZED_VALUE = Symbol();\nexport type UninitializedValue = typeof UNINITIALIZED_VALUE;","import { useEffect, useRef, useMemo } from './reactImports';\nimport { copyWithStructuralSharing } from './rtkqImports';\nexport function useStableQueryArgs<T>(queryArgs: T) {\n  const cache = useRef(queryArgs);\n  const copy = useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);\n  useEffect(() => {\n    if (cache.current !== copy) {\n      cache.current = copy;\n    }\n  }, [copy]);\n  return copy;\n}","import { useEffect, useRef } from './reactImports';\nimport { shallowEqual } from './reactReduxImports';\nexport function useShallowStableValue<T>(value: T) {\n  const cache = useRef(value);\n  useEffect(() => {\n    if (!shallowEqual(cache.current, value)) {\n      cache.current = value;\n    }\n  }, [value]);\n  return shallowEqual(cache.current, value) ? cache.current : value;\n}","// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nimport { buildCreateApi, coreModule } from './rtkqImports';\nimport { reactHooksModule, reactHooksModuleName } from './module';\nexport * from '@reduxjs/toolkit/query';\nexport { ApiProvider } from './ApiProvider';\nconst createApi = /* @__PURE__ */buildCreateApi(coreModule(), reactHooksModule());\nexport 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';\nexport { UNINITIALIZED_VALUE } from './constants';\nexport { createApi, reactHooksModule, reactHooksModuleName };","import { configureStore, formatProdErrorMessage as _formatProdErrorMessage } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport { useContext, useEffect } from './reactImports';\nimport * as React from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { Provider, ReactReduxContext } from './reactReduxImports';\nimport { setupListeners } from './rtkqImports';\nimport type { Api } from '@reduxjs/toolkit/query';\n\n/**\n * Can be used as a `Provider` if you **do not already have a Redux store**.\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Basic usage - wrap your App with ApiProvider\"\n * import * as React from 'react';\n * import { ApiProvider } from '@reduxjs/toolkit/query/react';\n * import { Pokemon } from './features/Pokemon';\n *\n * function App() {\n *   return (\n *     <ApiProvider api={api}>\n *       <Pokemon />\n *     </ApiProvider>\n *   );\n * }\n * ```\n *\n * @remarks\n * Using this together with an existing redux store, both will\n * conflict with each other - please use the traditional redux setup\n * in that case.\n */\nexport function ApiProvider(props: {\n  children: any;\n  api: Api<any, {}, any, any>;\n  setupListeners?: Parameters<typeof setupListeners>[1] | false;\n  context?: Context<ReactReduxContextValue | null>;\n}) {\n  const context = props.context || ReactReduxContext;\n  const existingContext = useContext(context);\n  if (existingContext) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(35) : 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.');\n  }\n  const [store] = React.useState(() => configureStore({\n    reducer: {\n      [props.api.reducerPath]: props.api.reducer\n    },\n    middleware: gDM => gDM().concat(props.api.middleware)\n  }));\n  // Adds the event listeners for online/offline/focus/etc\n  useEffect((): undefined | (() => void) => props.setupListeners === false ? undefined : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);\n  return <Provider store={store} context={context}>\n      {props.children}\n    </Provider>;\n}"],"mappings":";AAAA,SAAS,gBAAgB,YAAY,2BAA2B,gBAAgB,aAAa,iBAAiB;;;ACA9G,SAAS,0BAA0BA,gCAA+B;AAElE,SAAS,SAAS,SAAS,eAAe,eAAe,eAAe,eAAe,YAAY,kBAAkB;AAErH,SAAS,kBAAkB,uBAAuB;;;ACJ3C,SAAS,WAAW,KAAa;AACtC,SAAO,IAAI,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,EAAE,YAAY,CAAC;AACjD;;;ACGO,SAAS,gBAAgB,KAAuB;AACrD,MAAI,QAAQ;AACZ,aAAW,QAAQ,KAAK;AACtB;AAAA,EACF;AACA,SAAO;AACT;;;AC8XO,IAAM,iBAAiB;AACvB,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AA+c/B,SAAS,kBAAkB,GAA8G;AAC9I,SAAO,EAAE,SAAS;AACpB;AACO,SAAS,qBAAqB,GAAiH;AACpJ,SAAO,EAAE,SAAS;AACpB;AACO,SAAS,0BAA0B,GAA2H;AACnK,SAAO,EAAE,SAAS;AACpB;;;AC91BO,SAAS,WAA6B,WAAc,MAAqC;AAC9F,SAAO,OAAO,OAAO,QAAQ,GAAG,IAAI;AACtC;;;ACNA,SAAS,0BAA0B,yBAAyB,0BAA0B,0BAA0B,0BAA0B,gCAAgC;;;ACA1K,SAAS,WAAW,QAAQ,SAAS,YAAY,aAAa,eAAe,iBAAiB,gBAAgB;;;ACA9G,SAAS,cAAc,UAAU,yBAAyB;;;ACAnD,IAAM,sBAAsB,OAAO;;;ACEnC,SAAS,mBAAsB,WAAc;AAClD,QAAM,QAAQ,OAAO,SAAS;AAC9B,QAAM,OAAO,QAAQ,MAAM,0BAA0B,MAAM,SAAS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A;AAAA,YACF,CAAC;AACD,YAAC,IAAY,MAAM,WAAW,YAAY,CAAC,eAAe,IAAI;AAAA,UAChE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AWxMA,cAAc;;;ACLd,SAAS,gBAAgB,0BAA0BC,gCAA+B;AAGlF,YAAY,WAAW;AA8BhB,SAAS,YAAY,OAKzB;AACD,QAAM,UAAU,MAAM,WAAW;AACjC,QAAM,kBAAkB,WAAW,OAAO;AAC1C,MAAI,iBAAiB;AACnB,UAAM,IAAI,MAAM,QAAQ,IAAI,aAAa,eAAeC,yBAAwB,EAAE,IAAI,8GAA8G;AAAA,EACtM;AACA,QAAM,CAAC,KAAK,IAAU,eAAS,MAAM,eAAe;AAAA,IAClD,SAAS;AAAA,MACP,CAAC,MAAM,IAAI,WAAW,GAAG,MAAM,IAAI;AAAA,IACrC;AAAA,IACA,YAAY,SAAO,IAAI,EAAE,OAAO,MAAM,IAAI,UAAU;AAAA,EACtD,CAAC,CAAC;AAEF,YAAU,MAAgC,MAAM,mBAAmB,QAAQ,SAAY,eAAe,MAAM,UAAU,MAAM,cAAc,GAAG,CAAC,MAAM,gBAAgB,MAAM,QAAQ,CAAC;AACnL,SAAO,oCAAC,YAAS,OAAc,WAC1B,MAAM,QACT;AACJ;;;ADhDA,IAAM,YAA2B,+BAAe,WAAW,GAAG,iBAAiB,CAAC;","names":["_formatProdErrorMessage","arg","options","promise","_formatProdErrorMessage","_formatProdErrorMessage","_formatProdErrorMessage"]}
Index: node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+var ft=(y=>(y.uninitialized="uninitialized",y.pending="pending",y.fulfilled="fulfilled",y.rejected="rejected",y))(ft||{}),j="uninitialized",Ne="pending",Te="fulfilled",he="rejected";function et(e){return{status:e,isUninitialized:e===j,isLoading:e===Ne,isSuccess:e===Te,isError:e===he}}import{createAction as ee,createSlice as pe,createSelector as mt,createAsyncThunk as tt,combineReducers as gt,createNextState as Ie,isAnyOf as de,isAllOf as Ue,isAction as Qt,isPending as qe,isRejected as Re,isFulfilled as $,isRejectedWithValue as Ae,isAsyncThunkAction as nt,prepareAutoBatched as Se,SHOULD_AUTOBATCH as Ke,isPlainObject as ie,nanoid as Le}from"@reduxjs/toolkit";var Tt=ie;function _e(e,n){if(e===n||!(Tt(e)&&Tt(n)||Array.isArray(e)&&Array.isArray(n)))return n;let u=Object.keys(n),f=Object.keys(e),y=u.length===f.length,A=Array.isArray(n)?[]:{};for(let g of u)A[g]=_e(e[g],n[g]),y&&(y=e[g]===A[g]);return y?e:A}function Be(e,n,u){return e.reduce((f,y,A)=>(n(y,A)&&f.push(u(y,A)),f),[]).flat()}function ht(e){return new RegExp("(^|:)//").test(e)}function Rt(){return typeof document>"u"?!0:document.visibilityState!=="hidden"}function ke(e){return e!=null}function rt(e){return[...e?.values()??[]].filter(ke)}function At(){return typeof navigator>"u"||navigator.onLine===void 0?!0:navigator.onLine}var un=e=>e.replace(/\/$/,""),yn=e=>e.replace(/^\//,"");function St(e,n){if(!e)return n;if(!n)return e;if(ht(n))return n;let u=e.endsWith("/")||!n.startsWith("?")?"/":"";return e=un(e),n=yn(n),`${e}${u}${n}`}function ce(e,n,u){return e.has(n)?e.get(n):e.set(n,u(n)).get(n)}var Me=()=>new Map;var xt=e=>{let n=new AbortController;return setTimeout(()=>{let u="signal timed out",f="TimeoutError";n.abort(typeof DOMException<"u"?new DOMException(u,f):Object.assign(new Error(u),{name:f}))},e),n.signal},Dt=(...e)=>{for(let u of e)if(u.aborted)return AbortSignal.abort(u.reason);let n=new AbortController;for(let u of e)u.addEventListener("abort",()=>n.abort(u.reason),{signal:n.signal,once:!0});return n.signal};var Et=(...e)=>fetch(...e),pn=e=>e.status>=200&&e.status<=299,dn=e=>/ion\/(vnd\.api\+)?json/.test(e.get("content-type")||"");function bt(e){if(!ie(e))return e;let n={...e};for(let[u,f]of Object.entries(n))f===void 0&&delete n[u];return n}var cn=e=>typeof e=="object"&&(ie(e)||Array.isArray(e)||typeof e.toJSON=="function");function ln({baseUrl:e,prepareHeaders:n=T=>T,fetchFn:u=Et,paramsSerializer:f,isJsonContentType:y=dn,jsonContentType:A="application/json",jsonReplacer:g,timeout:B,responseHandler:k,validateStatus:S,...x}={}){return typeof fetch>"u"&&u===Et&&console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."),async(h,E,M)=>{let{getState:b,extra:c,endpoint:R,forced:I,type:s}=E,d,{url:i,headers:Q=new Headers(x.headers),params:D=void 0,responseHandler:m=k??"json",validateStatus:p=S??pn,timeout:a=B,...t}=typeof h=="string"?{url:h}:h,r={...x,signal:a?Dt(E.signal,xt(a)):E.signal,...t};Q=new Headers(bt(Q)),r.headers=await n(Q,{getState:b,arg:h,extra:c,endpoint:R,forced:I,type:s,extraOptions:M})||Q;let o=cn(r.body);if(r.body!=null&&!o&&typeof r.body!="string"&&r.headers.delete("content-type"),!r.headers.has("content-type")&&o&&r.headers.set("content-type",A),o&&y(r.headers)&&(r.body=JSON.stringify(r.body,g)),r.headers.has("accept")||(m==="json"?r.headers.set("accept","application/json"):m==="text"&&r.headers.set("accept","text/plain, text/html, */*")),D){let v=~i.indexOf("?")?"&":"?",L=f?f(D):new URLSearchParams(bt(D));i+=v+L}i=St(e,i);let l=new Request(i,r);d={request:new Request(i,r)};let w;try{w=await u(l)}catch(v){return{error:{status:(v instanceof Error||typeof DOMException<"u"&&v instanceof DOMException)&&v.name==="TimeoutError"?"TIMEOUT_ERROR":"FETCH_ERROR",error:String(v)},meta:d}}let O=w.clone();d.response=O;let F,P="";try{let v;if(await Promise.all([T(w,m).then(L=>F=L,L=>v=L),O.text().then(L=>P=L,()=>{})]),v)throw v}catch(v){return{error:{status:"PARSING_ERROR",originalStatus:w.status,data:P,error:String(v)},meta:d}}return p(w,F)?{data:F,meta:d}:{error:{status:w.status,data:F},meta:d}};async function T(h,E){if(typeof E=="function")return E(h);if(E==="content-type"&&(E=y(h.headers)?"json":"text"),E==="json"){let M=await h.text();return M.length?JSON.parse(M):null}return h.text()}}var G=class{constructor(n,u=void 0){this.value=n;this.meta=u}};async function fn(e=0,n=5,u){let f=Math.min(e,n),y=~~((Math.random()+.4)*(300<<f));await new Promise((A,g)=>{let B=setTimeout(()=>A(),y);if(u){let k=()=>{clearTimeout(B),g(new Error("Aborted"))};u.aborted?(clearTimeout(B),g(new Error("Aborted"))):u.addEventListener("abort",k,{once:!0})}})}function It(e,n){throw Object.assign(new G({error:e,meta:n}),{throwImmediately:!0})}function it(e){e.aborted&&It({status:"CUSTOM_ERROR",error:"Aborted"})}var Pt={},mn=(e,n)=>async(u,f,y)=>{let A=[5,(n||Pt).maxRetries,(y||Pt).maxRetries].filter(x=>x!==void 0),[g]=A.slice(-1),k={maxRetries:g,backoff:fn,retryCondition:(x,T,{attempt:h})=>h<=g,...n,...y},S=0;for(;;){it(f.signal);try{let x=await e(u,f,y);if(x.error)throw new G(x);return x}catch(x){if(S++,x.throwImmediately){if(x instanceof G)return x.value;throw x}if(x instanceof G){if(!k.retryCondition(x.value.error,u,{attempt:S,baseQueryApi:f,extraOptions:y}))return x.value}else if(S>k.maxRetries)return{error:x};it(f.signal);try{await k.backoff(S,k.maxRetries,f.signal)}catch(T){throw it(f.signal),T}}}},gn=Object.assign(mn,{fail:It});var Ve="__rtkq/",Bt="online",kt="offline",Qn="focus",Mt="focused",Tn="visibilitychange",ae=ee(`${Ve}${Mt}`),xe=ee(`${Ve}un${Mt}`),oe=ee(`${Ve}${Bt}`),De=ee(`${Ve}${kt}`),hn={onFocus:ae,onFocusLost:xe,onOnline:oe,onOffline:De},He=!1;function Rn(e,n){function u(){let[f,y,A,g]=[ae,xe,oe,De].map(x=>()=>e(x())),B=()=>{window.document.visibilityState==="visible"?f():y()},k=()=>{He=!1};if(!He&&typeof window<"u"&&window.addEventListener){let T=function(h){Object.entries(x).forEach(([E,M])=>{h?window.addEventListener(E,M,!1):window.removeEventListener(E,M)})};var S=T;let x={[Qn]:f,[Tn]:B,[Bt]:A,[kt]:g};T(!0),He=!0,k=()=>{T(!1),He=!1}}return k}return n?n(e,hn):u()}var te="query",at="mutation",ot="infinitequery";function le(e){return e.type===te}function wt(e){return e.type===at}function fe(e){return e.type===ot}function Ee(e){return le(e)||fe(e)}function we(e,n,u,f,y,A){let g=An(e)?e(n,u,f,y):e;return g?Be(g,ke,B=>A(st(B))):[]}function An(e){return typeof e=="function"}function st(e){return typeof e=="string"?{type:e}:e}import{current as Ct,isDraft as je,applyPatches as ut,original as Ft,isDraftable as vt,produceWithPatches as ze,enablePatches as Ot}from"immer";import"@reduxjs/toolkit";function Nt(e,n){return e.catch(n)}var Y=(e,n)=>e.endpointDefinitions[n];var be=Symbol("forceQueryFn"),Ce=e=>typeof e[be]=="function";function Ut({serializeQueryArgs:e,queryThunk:n,infiniteQueryThunk:u,mutationThunk:f,api:y,context:A,getInternalState:g}){let B=i=>g(i)?.runningQueries,k=i=>g(i)?.runningMutations,{unsubscribeQueryResult:S,removeMutationResult:x,updateSubscriptionOptions:T}=y.internalActions;return{buildInitiateQuery:I,buildInitiateInfiniteQuery:s,buildInitiateMutation:d,getRunningQueryThunk:h,getRunningMutationThunk:E,getRunningQueriesThunk:M,getRunningMutationsThunk:b};function h(i,Q){return D=>{let m=Y(A,i),p=e({queryArgs:Q,endpointDefinition:m,endpointName:i});return B(D)?.get(p)}}function E(i,Q){return D=>k(D)?.get(Q)}function M(){return i=>rt(B(i))}function b(){return i=>rt(k(i))}function c(i){}function R(i,Q){let D=(m,{subscribe:p=!0,forceRefetch:a,subscriptionOptions:t,[be]:r,...o}={})=>(l,C)=>{let w=e({queryArgs:m,endpointDefinition:Q,endpointName:i}),O,F={...o,type:te,subscribe:p,forceRefetch:a,subscriptionOptions:t,endpointName:i,originalArgs:m,queryCacheKey:w,[be]:r};if(le(Q))O=n(F);else{let{direction:q,initialPageParam:K,refetchCachedPages:N}=o;O=u({...F,direction:q,initialPageParam:K,refetchCachedPages:N})}let P=y.endpoints[i].select(m),v=l(O),L=P(C());let{requestId:z,abort:J}=v,_=L.requestId!==z,V=B(l)?.get(w),H=()=>P(C()),U=Object.assign(r?v.then(H):_&&!V?Promise.resolve(L):Promise.all([V,v]).then(H),{arg:m,requestId:z,subscriptionOptions:t,queryCacheKey:w,abort:J,async unwrap(){let q=await U;if(q.isError)throw q.error;return q.data},refetch:q=>l(D(m,{subscribe:!1,forceRefetch:!0,...q})),unsubscribe(){p&&l(S({queryCacheKey:w,requestId:z}))},updateSubscriptionOptions(q){U.subscriptionOptions=q,l(T({endpointName:i,requestId:z,queryCacheKey:w,options:q}))}});if(!V&&!_&&!r){let q=B(l);q.set(w,U),U.then(()=>{q.delete(w)})}return U};return D}function I(i,Q){return R(i,Q)}function s(i,Q){return R(i,Q)}function d(i){return(Q,{track:D=!0,fixedCacheKey:m}={})=>(p,a)=>{let t=f({type:"mutation",endpointName:i,originalArgs:Q,track:D,fixedCacheKey:m}),r=p(t);let{requestId:o,abort:l,unwrap:C}=r,w=Nt(r.unwrap().then(v=>({data:v})),v=>({error:v})),O=()=>{p(x({requestId:o,fixedCacheKey:m}))},F=Object.assign(w,{arg:r.arg,requestId:o,abort:l,unwrap:C,reset:O}),P=k(p);return P.set(o,F),F.then(()=>{P.delete(o)}),m&&(P.set(m,F),F.then(()=>{P.get(m)===F&&P.delete(m)})),F}}}import{SchemaError as Sn}from"@standard-schema/utils";var Pe=class extends Sn{constructor(u,f,y,A){super(u);this.value=f;this.schemaName=y;this._bqMeta=A}},se=(e,n)=>Array.isArray(e)?e.includes(n):!!e;async function ue(e,n,u,f){let y=await e["~standard"].validate(n);if(y.issues)throw new Pe(y.issues,n,u,f);return y.value}function qt(e){return e}var Fe=(e={})=>({...e,[Ke]:!0});function Kt({reducerPath:e,baseQuery:n,context:{endpointDefinitions:u},serializeQueryArgs:f,api:y,assertTagType:A,selectors:g,onSchemaFailure:B,catchSchemaFailure:k,skipSchemaValidation:S}){let x=(t,r,o,l)=>(C,w)=>{let O=u[t],F=f({queryArgs:r,endpointDefinition:O,endpointName:t});if(C(y.internalActions.queryResultPatched({queryCacheKey:F,patches:o})),!l)return;let P=y.endpoints[t].select(r)(w()),v=we(O.providesTags,P.data,void 0,r,{},A);C(y.internalActions.updateProvidedBy([{queryCacheKey:F,providedTags:v}]))};function T(t,r,o=0){let l=[r,...t];return o&&l.length>o?l.slice(0,-1):l}function h(t,r,o=0){let l=[...t,r];return o&&l.length>o?l.slice(1):l}let E=(t,r,o,l=!0)=>(C,w)=>{let F=y.endpoints[t].select(r)(w()),P={patches:[],inversePatches:[],undo:()=>C(y.util.patchQueryData(t,r,P.inversePatches,l))};if(F.status===j)return P;let v;if("data"in F)if(vt(F.data)){let[L,z,J]=ze(F.data,o);P.patches.push(...z),P.inversePatches.push(...J),v=L}else v=o(F.data),P.patches.push({op:"replace",path:[],value:v}),P.inversePatches.push({op:"replace",path:[],value:F.data});return P.patches.length===0||C(y.util.patchQueryData(t,r,P.patches,l)),P},M=(t,r,o)=>l=>l(y.endpoints[t].initiate(r,{subscribe:!1,forceRefetch:!0,[be]:()=>({data:o})})),b=(t,r)=>t.query&&t[r]?t[r]:qt,c=async(t,{signal:r,abort:o,rejectWithValue:l,fulfillWithValue:C,dispatch:w,getState:O,extra:F})=>{let P=u[t.endpointName],{metaSchema:v,skipSchemaValidation:L=S}=P,z=t.type===te;try{let J=qt,_={signal:r,abort:o,dispatch:w,getState:O,extra:F,endpoint:t.endpointName,type:t.type,forced:z?R(t,O()):void 0,queryCacheKey:z?t.queryCacheKey:void 0},V=z?t[be]:void 0,H,U=async(K,N,ne,W)=>{if(N==null&&K.pages.length)return Promise.resolve({data:K});let ge={queryArg:t.originalArgs,pageParam:N},X=await q(ge),Qe=W?T:h;return{data:{pages:Qe(K.pages,X.data,ne),pageParams:Qe(K.pageParams,N,ne)},meta:X.meta}};async function q(K){let N,{extraOptions:ne,argSchema:W,rawResponseSchema:ge,responseSchema:X}=P;if(W&&!se(L,"arg")&&(K=await ue(W,K,"argSchema",{})),V?N=V():P.query?(J=b(P,"transformResponse"),N=await n(P.query(K),_,ne)):N=await P.queryFn(K,_,ne,ye=>n(ye,_,ne)),N.error)throw new G(N.error,N.meta);let{data:Qe}=N;ge&&!se(L,"rawResponse")&&(Qe=await ue(ge,N.data,"rawResponseSchema",N.meta));let re=await J(Qe,N.meta,K);return X&&!se(L,"response")&&(re=await ue(X,re,"responseSchema",N.meta)),{...N,data:re}}if(z&&"infiniteQueryOptions"in P){let{infiniteQueryOptions:K}=P,{maxPages:N=1/0}=K,ne=t.refetchCachedPages??K.refetchCachedPages??!0,W,ge={pages:[],pageParams:[]},X=g.selectQueryEntry(O(),t.queryCacheKey)?.data,re=R(t,O())&&!t.direction||!X?ge:X;if("direction"in t&&t.direction&&re.pages.length){let ye=t.direction==="backward",Oe=(ye?yt:We)(K,re,t.originalArgs);W=await U(re,Oe,N,ye)}else{let{initialPageParam:ye=K.initialPageParam}=t,ve=X?.pageParams??[],Oe=ve[0]??ye,on=ve.length;if(W=await U(re,Oe,N),V&&(W={data:W.data.pages[0]}),ne)for(let lt=1;lt<on;lt++){let sn=We(K,W.data,t.originalArgs);W=await U(W.data,sn,N)}}H=W}else H=await q(t.originalArgs);return v&&!se(L,"meta")&&H.meta&&(H.meta=await ue(v,H.meta,"metaSchema",H.meta)),C(H.data,Fe({fulfilledTimeStamp:Date.now(),baseQueryMeta:H.meta}))}catch(J){let _=J;if(_ instanceof G){let V=b(P,"transformErrorResponse"),{rawErrorResponseSchema:H,errorResponseSchema:U}=P,{value:q,meta:K}=_;try{H&&!se(L,"rawErrorResponse")&&(q=await ue(H,q,"rawErrorResponseSchema",K)),v&&!se(L,"meta")&&(K=await ue(v,K,"metaSchema",K));let N=await V(q,K,t.originalArgs);return U&&!se(L,"errorResponse")&&(N=await ue(U,N,"errorResponseSchema",K)),l(N,Fe({baseQueryMeta:K}))}catch(N){_=N}}try{if(_ instanceof Pe){let V={endpoint:t.endpointName,arg:t.originalArgs,type:t.type,queryCacheKey:z?t.queryCacheKey:void 0};P.onSchemaFailure?.(_,V),B?.(_,V);let{catchSchemaFailure:H=k}=P;if(H)return l(H(_,V),Fe({baseQueryMeta:_._bqMeta}))}}catch(V){_=V}throw console.error(_),_}};function R(t,r){let o=g.selectQueryEntry(r,t.queryCacheKey),l=g.selectConfig(r).refetchOnMountOrArgChange,C=o?.fulfilledTimeStamp,w=t.forceRefetch??(t.subscribe&&l);return w?w===!0||(Number(new Date)-Number(C))/1e3>=w:!1}let I=()=>tt(`${e}/executeQuery`,c,{getPendingMeta({arg:r}){let o=u[r.endpointName];return Fe({startedTimeStamp:Date.now(),...fe(o)?{direction:r.direction}:{}})},condition(r,{getState:o}){let l=o(),C=g.selectQueryEntry(l,r.queryCacheKey),w=C?.fulfilledTimeStamp,O=r.originalArgs,F=C?.originalArgs,P=u[r.endpointName],v=r.direction;return Ce(r)?!0:C?.status==="pending"?!1:R(r,l)||le(P)&&P?.forceRefetch?.({currentArg:O,previousArg:F,endpointState:C,state:l})?!0:!(w&&!v)},dispatchConditionRejection:!0}),s=I(),d=I(),i=tt(`${e}/executeMutation`,c,{getPendingMeta(){return Fe({startedTimeStamp:Date.now()})}}),Q=t=>"force"in t,D=t=>"ifOlderThan"in t,m=(t,r,o={})=>(l,C)=>{let w=Q(o)&&o.force,O=D(o)&&o.ifOlderThan,F=(v=!0)=>{let L={forceRefetch:v,subscribe:!1};return y.endpoints[t].initiate(r,L)},P=y.endpoints[t].select(r)(C());if(w)l(F());else if(O){let v=P?.fulfilledTimeStamp;if(!v){l(F());return}(Number(new Date)-Number(new Date(v)))/1e3>=O&&l(F())}else l(F(!1))};function p(t){return r=>r?.meta?.arg?.endpointName===t}function a(t,r){return{matchPending:Ue(qe(t),p(r)),matchFulfilled:Ue($(t),p(r)),matchRejected:Ue(Re(t),p(r))}}return{queryThunk:s,mutationThunk:i,infiniteQueryThunk:d,prefetch:m,updateQueryData:E,upsertQueryData:M,patchQueryData:x,buildMatchThunkActions:a}}function We(e,{pages:n,pageParams:u},f){let y=n.length-1;return e.getNextPageParam(n[y],n,u[y],u,f)}function yt(e,{pages:n,pageParams:u},f){return e.getPreviousPageParam?.(n[0],n,u[0],u,f)}function $e(e,n,u,f){return we(u[e.meta.arg.endpointName][n],$(e)?e.payload:void 0,Ae(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,f)}function pt(e){return je(e)?Ct(e):e}function Ye(e,n,u){let f=e[n];f&&u(f)}function me(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Lt(e,n,u){let f=e[me(n)];f&&u(f)}var Je={};function _t({reducerPath:e,queryThunk:n,mutationThunk:u,serializeQueryArgs:f,context:{endpointDefinitions:y,apiUid:A,extractRehydrationInfo:g,hasRehydrationInfo:B},assertTagType:k,config:S}){let x=ee(`${e}/resetApiState`);function T(p,a,t,r){p[a.queryCacheKey]??={status:j,endpointName:a.endpointName},Ye(p,a.queryCacheKey,o=>{o.status=Ne,o.requestId=t&&o.requestId?o.requestId:r.requestId,a.originalArgs!==void 0&&(o.originalArgs=a.originalArgs),o.startedTimeStamp=r.startedTimeStamp;let l=y[r.arg.endpointName];fe(l)&&"direction"in a&&(o.direction=a.direction)})}function h(p,a,t,r){Ye(p,a.arg.queryCacheKey,o=>{if(o.requestId!==a.requestId&&!r)return;let{merge:l}=y[a.arg.endpointName];if(o.status=Te,l)if(o.data!==void 0){let{fulfilledTimeStamp:C,arg:w,baseQueryMeta:O,requestId:F}=a,P=Ie(o.data,v=>l(v,t,{arg:w.originalArgs,baseQueryMeta:O,fulfilledTimeStamp:C,requestId:F}));o.data=P}else o.data=t;else o.data=y[a.arg.endpointName].structuralSharing??!0?_e(je(o.data)?Ft(o.data):o.data,t):t;delete o.error,o.fulfilledTimeStamp=a.fulfilledTimeStamp})}let E=pe({name:`${e}/queries`,initialState:Je,reducers:{removeQueryResult:{reducer(p,{payload:{queryCacheKey:a}}){delete p[a]},prepare:Se()},cacheEntriesUpserted:{reducer(p,a){for(let t of a.payload){let{queryDescription:r,value:o}=t;T(p,r,!0,{arg:r,requestId:a.meta.requestId,startedTimeStamp:a.meta.timestamp}),h(p,{arg:r,requestId:a.meta.requestId,fulfilledTimeStamp:a.meta.timestamp,baseQueryMeta:{}},o,!0)}},prepare:p=>({payload:p.map(r=>{let{endpointName:o,arg:l,value:C}=r,w=y[o];return{queryDescription:{type:te,endpointName:o,originalArgs:r.arg,queryCacheKey:f({queryArgs:l,endpointDefinition:w,endpointName:o})},value:C}}),meta:{[Ke]:!0,requestId:Le(),timestamp:Date.now()}})},queryResultPatched:{reducer(p,{payload:{queryCacheKey:a,patches:t}}){Ye(p,a,r=>{r.data=ut(r.data,t.concat())})},prepare:Se()}},extraReducers(p){p.addCase(n.pending,(a,{meta:t,meta:{arg:r}})=>{let o=Ce(r);T(a,r,o,t)}).addCase(n.fulfilled,(a,{meta:t,payload:r})=>{let o=Ce(t.arg);h(a,t,r,o)}).addCase(n.rejected,(a,{meta:{condition:t,arg:r,requestId:o},error:l,payload:C})=>{Ye(a,r.queryCacheKey,w=>{if(!t){if(w.requestId!==o)return;w.status=he,w.error=C??l}})}).addMatcher(B,(a,t)=>{let{queries:r}=g(t);for(let[o,l]of Object.entries(r))(l?.status===Te||l?.status===he)&&(a[o]=l)})}}),M=pe({name:`${e}/mutations`,initialState:Je,reducers:{removeMutationResult:{reducer(p,{payload:a}){let t=me(a);t in p&&delete p[t]},prepare:Se()}},extraReducers(p){p.addCase(u.pending,(a,{meta:t,meta:{requestId:r,arg:o,startedTimeStamp:l}})=>{o.track&&(a[me(t)]={requestId:r,status:Ne,endpointName:o.endpointName,startedTimeStamp:l})}).addCase(u.fulfilled,(a,{payload:t,meta:r})=>{r.arg.track&&Lt(a,r,o=>{o.requestId===r.requestId&&(o.status=Te,o.data=t,o.fulfilledTimeStamp=r.fulfilledTimeStamp)})}).addCase(u.rejected,(a,{payload:t,error:r,meta:o})=>{o.arg.track&&Lt(a,o,l=>{l.requestId===o.requestId&&(l.status=he,l.error=t??r)})}).addMatcher(B,(a,t)=>{let{mutations:r}=g(t);for(let[o,l]of Object.entries(r))(l?.status===Te||l?.status===he)&&o!==l?.requestId&&(a[o]=l)})}}),b={tags:{},keys:{}},c=pe({name:`${e}/invalidation`,initialState:b,reducers:{updateProvidedBy:{reducer(p,a){for(let{queryCacheKey:t,providedTags:r}of a.payload){R(p,t);for(let{type:o,id:l}of r){let C=(p.tags[o]??={})[l||"__internal_without_id"]??=[];C.includes(t)||C.push(t)}p.keys[t]=r}},prepare:Se()}},extraReducers(p){p.addCase(E.actions.removeQueryResult,(a,{payload:{queryCacheKey:t}})=>{R(a,t)}).addMatcher(B,(a,t)=>{let{provided:r}=g(t);for(let[o,l]of Object.entries(r.tags??{}))for(let[C,w]of Object.entries(l)){let O=(a.tags[o]??={})[C||"__internal_without_id"]??=[];for(let F of w)O.includes(F)||O.push(F),a.keys[F]=r.keys[F]}}).addMatcher(de($(n),Ae(n)),(a,t)=>{I(a,[t])}).addMatcher(E.actions.cacheEntriesUpserted.match,(a,t)=>{let r=t.payload.map(({queryDescription:o,value:l})=>({type:"UNKNOWN",payload:l,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:o}}));I(a,r)})}});function R(p,a){let t=pt(p.keys[a]??[]);for(let r of t){let o=r.type,l=r.id??"__internal_without_id",C=p.tags[o]?.[l];C&&(p.tags[o][l]=pt(C).filter(w=>w!==a))}delete p.keys[a]}function I(p,a){let t=a.map(r=>{let o=$e(r,"providesTags",y,k),{queryCacheKey:l}=r.meta.arg;return{queryCacheKey:l,providedTags:o}});c.caseReducers.updateProvidedBy(p,c.actions.updateProvidedBy(t))}let s=pe({name:`${e}/subscriptions`,initialState:Je,reducers:{updateSubscriptionOptions(p,a){},unsubscribeQueryResult(p,a){},internal_getRTKQSubscriptions(){}}}),d=pe({name:`${e}/internalSubscriptions`,initialState:Je,reducers:{subscriptionsUpdated:{reducer(p,a){return ut(p,a.payload)},prepare:Se()}}}),i=pe({name:`${e}/config`,initialState:{online:At(),focused:Rt(),middlewareRegistered:!1,...S},reducers:{middlewareRegistered(p,{payload:a}){p.middlewareRegistered=p.middlewareRegistered==="conflict"||A!==a?"conflict":!0}},extraReducers:p=>{p.addCase(oe,a=>{a.online=!0}).addCase(De,a=>{a.online=!1}).addCase(ae,a=>{a.focused=!0}).addCase(xe,a=>{a.focused=!1}).addMatcher(B,a=>({...a}))}}),Q=gt({queries:E.reducer,mutations:M.reducer,provided:c.reducer,subscriptions:d.reducer,config:i.reducer}),D=(p,a)=>Q(x.match(a)?void 0:p,a),m={...i.actions,...E.actions,...s.actions,...d.actions,...M.actions,...c.actions,resetApiState:x};return{reducer:D,actions:m}}var Ge=Symbol.for("RTKQ/skipToken"),jt={status:j},Ht=Ie(jt,()=>{}),Vt=Ie(jt,()=>{});function zt({serializeQueryArgs:e,reducerPath:n,createSelector:u}){let f=s=>Ht,y=s=>Vt;return{buildQuerySelector:h,buildInfiniteQuerySelector:E,buildMutationSelector:M,selectInvalidatedBy:b,selectCachedArgsForQuery:c,selectApiState:g,selectQueries:B,selectMutations:S,selectQueryEntry:k,selectConfig:x};function A(s){return{...s,...et(s.status)}}function g(s){return s[n]}function B(s){return g(s)?.queries}function k(s,d){return B(s)?.[d]}function S(s){return g(s)?.mutations}function x(s){return g(s)?.config}function T(s,d,i){return Q=>{if(Q===Ge)return u(f,i);let D=e({queryArgs:Q,endpointDefinition:d,endpointName:s});return u(p=>k(p,D)??Ht,i)}}function h(s,d){return T(s,d,A)}function E(s,d){let{infiniteQueryOptions:i}=d;function Q(D){let m={...D,...et(D.status)},{isLoading:p,isError:a,direction:t}=m,r=t==="forward",o=t==="backward";return{...m,hasNextPage:R(i,m.data,m.originalArgs),hasPreviousPage:I(i,m.data,m.originalArgs),isFetchingNextPage:p&&r,isFetchingPreviousPage:p&&o,isFetchNextPageError:a&&r,isFetchPreviousPageError:a&&o}}return T(s,d,Q)}function M(){return s=>{let d;return typeof s=="object"?d=me(s)??Ge:d=s,u(d===Ge?y:D=>g(D)?.mutations?.[d]??Vt,A)}}function b(s,d){let i=s[n],Q=new Set,D=Be(d,ke,st);for(let m of D){let p=i.provided.tags[m.type];if(!p)continue;let a=(m.id!==void 0?p[m.id]:Object.values(p).flat())??[];for(let t of a)Q.add(t)}return Array.from(Q.values()).flatMap(m=>{let p=i.queries[m];return p?{queryCacheKey:m,endpointName:p.endpointName,originalArgs:p.originalArgs}:[]})}function c(s,d){return Be(Object.values(B(s)),i=>i?.endpointName===d&&i.status!==j,i=>i.originalArgs)}function R(s,d,i){return d?We(s,d,i)!=null:!1}function I(s,d,i){return!d||!s.getPreviousPageParam?!1:yt(s,d,i)!=null}}import{formatProdErrorMessage as xn}from"@reduxjs/toolkit";var Wt=WeakMap?new WeakMap:void 0,Ze=({endpointName:e,queryArgs:n})=>{let u="",f=Wt?.get(n);if(typeof f=="string")u=f;else{let y=JSON.stringify(n,(A,g)=>(g=typeof g=="bigint"?{$bigint:g.toString()}:g,g=ie(g)?Object.keys(g).sort().reduce((B,k)=>(B[k]=g[k],B),{}):g,g));ie(n)&&Wt?.set(n,y),u=y}return`${e}(${u})`};import{weakMapMemoize as $t}from"reselect";function dt(...e){return function(u){let f=$t(S=>u.extractRehydrationInfo?.(S,{reducerPath:u.reducerPath??"api"})),y={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...u,extractRehydrationInfo:f,serializeQueryArgs(S){let x=Ze;if("serializeQueryArgs"in S.endpointDefinition){let T=S.endpointDefinition.serializeQueryArgs;x=h=>{let E=T(h);return typeof E=="string"?E:Ze({...h,queryArgs:E})}}else u.serializeQueryArgs&&(x=u.serializeQueryArgs);return x(S)},tagTypes:[...u.tagTypes||[]]},A={endpointDefinitions:{},batch(S){S()},apiUid:Le(),extractRehydrationInfo:f,hasRehydrationInfo:$t(S=>f(S)!=null)},g={injectEndpoints:k,enhanceEndpoints({addTagTypes:S,endpoints:x}){if(S)for(let T of S)y.tagTypes.includes(T)||y.tagTypes.push(T);if(x)for(let[T,h]of Object.entries(x))typeof h=="function"?h(Y(A,T)):Object.assign(Y(A,T)||{},h);return g}},B=e.map(S=>S.init(g,y,A));function k(S){let x=S.endpoints({query:T=>({...T,type:te}),mutation:T=>({...T,type:at}),infiniteQuery:T=>({...T,type:ot})});for(let[T,h]of Object.entries(x)){if(S.overrideExisting!==!0&&T in A.endpointDefinitions){if(S.overrideExisting==="throw")throw new Error(xn(39));continue}A.endpointDefinitions[T]=h;for(let E of B)E.injectEndpoint(T,h)}return g}return g.injectEndpoints({endpoints:u.endpoints})}}import{formatProdErrorMessage as Dn}from"@reduxjs/toolkit";var En=Symbol();function bn(){return function(){throw new Error(Dn(33))}}function Z(e,...n){return Object.assign(e,...n)}var Yt=({api:e,queryThunk:n,internalState:u,mwApi:f})=>{let y=`${e.reducerPath}/subscriptions`,A=null,g=null,{updateSubscriptionOptions:B,unsubscribeQueryResult:k}=e.internalActions,S=(b,c)=>{if(B.match(c)){let{queryCacheKey:I,requestId:s,options:d}=c.payload,i=b.get(I);return i?.has(s)&&i.set(s,d),!0}if(k.match(c)){let{queryCacheKey:I,requestId:s}=c.payload,d=b.get(I);return d&&d.delete(s),!0}if(e.internalActions.removeQueryResult.match(c))return b.delete(c.payload.queryCacheKey),!0;if(n.pending.match(c)){let{meta:{arg:I,requestId:s}}=c,d=ce(b,I.queryCacheKey,Me);return I.subscribe&&d.set(s,I.subscriptionOptions??d.get(s)??{}),!0}let R=!1;if(n.rejected.match(c)){let{meta:{condition:I,arg:s,requestId:d}}=c;if(I&&s.subscribe){let i=ce(b,s.queryCacheKey,Me);i.set(d,s.subscriptionOptions??i.get(d)??{}),R=!0}}return R},x=()=>u.currentSubscriptions,E={getSubscriptions:x,getSubscriptionCount:b=>x().get(b)?.size??0,isRequestSubscribed:(b,c)=>!!x()?.get(b)?.get(c)};function M(b){return JSON.parse(JSON.stringify(Object.fromEntries([...b].map(([c,R])=>[c,Object.fromEntries(R)]))))}return(b,c)=>{if(A||(A=M(u.currentSubscriptions)),e.util.resetApiState.match(b))return A={},u.currentSubscriptions.clear(),g=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(b))return[!1,E];let R=S(u.currentSubscriptions,b),I=!0;if(R){g||(g=setTimeout(()=>{let i=M(u.currentSubscriptions),[,Q]=ze(A,()=>i);c.next(e.internalActions.subscriptionsUpdated(Q)),A=i,g=null},500));let s=typeof b.type=="string"&&!!b.type.startsWith(y),d=n.rejected.match(b)&&b.meta.condition&&!!b.meta.arg.subscribe;I=!s&&!d}return[I,!1]}};var Pn=2147483647/1e3-1,Jt=({reducerPath:e,api:n,queryThunk:u,context:f,internalState:y,selectors:{selectQueryEntry:A,selectConfig:g},getRunningQueryThunk:B,mwApi:k})=>{let{removeQueryResult:S,unsubscribeQueryResult:x,cacheEntriesUpserted:T}=n.internalActions,h=de(x.match,u.fulfilled,u.rejected,T.match);function E(s){let d=y.currentSubscriptions.get(s);return d?d.size>0:!1}let M={};function b(s){for(let d of s.values())d?.abort?.()}let c=(s,d)=>{let i=d.getState(),Q=g(i);if(h(s)){let D;if(T.match(s))D=s.payload.map(m=>m.queryDescription.queryCacheKey);else{let{queryCacheKey:m}=x.match(s)?s.payload:s.meta.arg;D=[m]}R(D,d,Q)}if(n.util.resetApiState.match(s)){for(let[D,m]of Object.entries(M))m&&clearTimeout(m),delete M[D];b(y.runningQueries),b(y.runningMutations)}if(f.hasRehydrationInfo(s)){let{queries:D}=f.extractRehydrationInfo(s);R(Object.keys(D),d,Q)}};function R(s,d,i){let Q=d.getState();for(let D of s){let m=A(Q,D);m?.endpointName&&I(D,m.endpointName,d,i)}}function I(s,d,i,Q){let m=Y(f,d)?.keepUnusedDataFor??Q.keepUnusedDataFor;if(m===1/0)return;let p=Math.max(0,Math.min(m,Pn));if(!E(s)){let a=M[s];a&&clearTimeout(a),M[s]=setTimeout(()=>{if(!E(s)){let t=A(i.getState(),s);t?.endpointName&&i.dispatch(B(t.endpointName,t.originalArgs))?.abort(),i.dispatch(S({queryCacheKey:s}))}delete M[s]},p*1e3)}}return c};var Gt=new Error("Promise never resolved before cacheEntryRemoved."),Zt=({api:e,reducerPath:n,context:u,queryThunk:f,mutationThunk:y,internalState:A,selectors:{selectQueryEntry:g,selectApiState:B}})=>{let k=nt(f),S=nt(y),x=$(f,y),T={},{removeQueryResult:h,removeMutationResult:E,cacheEntriesUpserted:M}=e.internalActions;function b(i,Q,D){let m=T[i];m?.valueResolved&&(m.valueResolved({data:Q,meta:D}),delete m.valueResolved)}function c(i){let Q=T[i];Q&&(delete T[i],Q.cacheEntryRemoved())}function R(i){let{arg:Q,requestId:D}=i.meta,{endpointName:m,originalArgs:p}=Q;return[m,p,D]}let I=(i,Q,D)=>{let m=s(i);function p(a,t,r,o){let l=g(D,t),C=g(Q.getState(),t);!l&&C&&d(a,o,t,Q,r)}if(f.pending.match(i)){let[a,t,r]=R(i);p(a,m,r,t)}else if(M.match(i))for(let{queryDescription:a,value:t}of i.payload){let{endpointName:r,originalArgs:o,queryCacheKey:l}=a;p(r,l,i.meta.requestId,o),b(l,t,{})}else if(y.pending.match(i)){if(Q.getState()[n].mutations[m]){let[t,r,o]=R(i);d(t,r,m,Q,o)}}else if(x(i))b(m,i.payload,i.meta.baseQueryMeta);else if(h.match(i)||E.match(i))c(m);else if(e.util.resetApiState.match(i))for(let a of Object.keys(T))c(a)};function s(i){return k(i)?i.meta.arg.queryCacheKey:S(i)?i.meta.arg.fixedCacheKey??i.meta.requestId:h.match(i)?i.payload.queryCacheKey:E.match(i)?me(i.payload):""}function d(i,Q,D,m,p){let a=Y(u,i),t=a?.onCacheEntryAdded;if(!t)return;let r={},o=new Promise(P=>{r.cacheEntryRemoved=P}),l=Promise.race([new Promise(P=>{r.valueResolved=P}),o.then(()=>{throw Gt})]);l.catch(()=>{}),T[D]=r;let C=e.endpoints[i].select(Ee(a)?Q:D),w=m.dispatch((P,v,L)=>L),O={...m,getCacheEntry:()=>C(m.getState()),requestId:p,extra:w,updateCachedData:Ee(a)?P=>m.dispatch(e.util.updateQueryData(i,Q,P)):void 0,cacheDataLoaded:l,cacheEntryRemoved:o},F=t(Q,O);Promise.resolve(F).catch(P=>{if(P!==Gt)throw P})}return I};var Xt=({api:e,context:{apiUid:n},reducerPath:u})=>(f,y)=>{e.util.resetApiState.match(f)&&y.dispatch(e.internalActions.middlewareRegistered(n))};var en=({reducerPath:e,context:n,context:{endpointDefinitions:u},mutationThunk:f,queryThunk:y,api:A,assertTagType:g,refetchQuery:B,internalState:k})=>{let{removeQueryResult:S}=A.internalActions,x=de($(f),Ae(f)),T=de($(y,f),Re(y,f)),h=[],E=0,M=(R,I)=>{(y.pending.match(R)||f.pending.match(R))&&E++,T(R)&&(E=Math.max(0,E-1)),x(R)?c($e(R,"invalidatesTags",u,g),I):T(R)?c([],I):A.util.invalidateTags.match(R)&&c(we(R.payload,void 0,void 0,void 0,void 0,g),I)};function b(){return E>0}function c(R,I){let s=I.getState(),d=s[e];if(h.push(...R),d.config.invalidationBehavior==="delayed"&&b())return;let i=h;if(h=[],i.length===0)return;let Q=A.util.selectInvalidatedBy(s,i);n.batch(()=>{let D=Array.from(Q.values());for(let{queryCacheKey:m}of D){let p=d.queries[m],a=ce(k.currentSubscriptions,m,Me);p&&(a.size===0?I.dispatch(S({queryCacheKey:m})):p.status!==j&&I.dispatch(B(p)))}})}return M};var tn=({reducerPath:e,queryThunk:n,api:u,refetchQuery:f,internalState:y})=>{let{currentPolls:A,currentSubscriptions:g}=y,B=new Set,k=null,S=(c,R)=>{(u.internalActions.updateSubscriptionOptions.match(c)||u.internalActions.unsubscribeQueryResult.match(c))&&x(c.payload.queryCacheKey,R),(n.pending.match(c)||n.rejected.match(c)&&c.meta.condition)&&x(c.meta.arg.queryCacheKey,R),(n.fulfilled.match(c)||n.rejected.match(c)&&!c.meta.condition)&&T(c.meta.arg,R),u.util.resetApiState.match(c)&&(M(),k&&(clearTimeout(k),k=null),B.clear())};function x(c,R){B.add(c),k||(k=setTimeout(()=>{for(let I of B)h({queryCacheKey:I},R);B.clear(),k=null},0))}function T({queryCacheKey:c},R){let I=R.getState()[e],s=I.queries[c],d=g.get(c);if(!s||s.status===j)return;let{lowestPollingInterval:i,skipPollingIfUnfocused:Q}=b(d);if(!Number.isFinite(i))return;let D=A.get(c);D?.timeout&&(clearTimeout(D.timeout),D.timeout=void 0);let m=Date.now()+i;A.set(c,{nextPollTimestamp:m,pollingInterval:i,timeout:setTimeout(()=>{(I.config.focused||!Q)&&R.dispatch(f(s)),T({queryCacheKey:c},R)},i)})}function h({queryCacheKey:c},R){let s=R.getState()[e].queries[c],d=g.get(c);if(!s||s.status===j)return;let{lowestPollingInterval:i}=b(d);if(!Number.isFinite(i)){E(c);return}let Q=A.get(c),D=Date.now()+i;(!Q||D<Q.nextPollTimestamp)&&T({queryCacheKey:c},R)}function E(c){let R=A.get(c);R?.timeout&&clearTimeout(R.timeout),A.delete(c)}function M(){for(let c of A.keys())E(c)}function b(c=new Map){let R=!1,I=Number.POSITIVE_INFINITY;for(let s of c.values())s.pollingInterval&&(I=Math.min(s.pollingInterval,I),R=s.skipPollingIfUnfocused||R);return{lowestPollingInterval:I,skipPollingIfUnfocused:R}}return S};var nn=({api:e,context:n,queryThunk:u,mutationThunk:f})=>{let y=qe(u,f),A=Re(u,f),g=$(u,f),B={};return(S,x)=>{if(y(S)){let{requestId:T,arg:{endpointName:h,originalArgs:E}}=S.meta,M=Y(n,h),b=M?.onQueryStarted;if(b){let c={},R=new Promise((i,Q)=>{c.resolve=i,c.reject=Q});R.catch(()=>{}),B[T]=c;let I=e.endpoints[h].select(Ee(M)?E:T),s=x.dispatch((i,Q,D)=>D),d={...x,getCacheEntry:()=>I(x.getState()),requestId:T,extra:s,updateCachedData:Ee(M)?i=>x.dispatch(e.util.updateQueryData(h,E,i)):void 0,queryFulfilled:R};b(E,d)}}else if(g(S)){let{requestId:T,baseQueryMeta:h}=S.meta;B[T]?.resolve({data:S.payload,meta:h}),delete B[T]}else if(A(S)){let{requestId:T,rejectedWithValue:h,baseQueryMeta:E}=S.meta;B[T]?.reject({error:S.payload??S.error,isUnhandledError:!h,meta:E}),delete B[T]}}};var rn=({reducerPath:e,context:n,api:u,refetchQuery:f,internalState:y})=>{let{removeQueryResult:A}=u.internalActions,g=(k,S)=>{ae.match(k)&&B(S,"refetchOnFocus"),oe.match(k)&&B(S,"refetchOnReconnect")};function B(k,S){let x=k.getState()[e],T=x.queries,h=y.currentSubscriptions;n.batch(()=>{for(let E of h.keys()){let M=T[E],b=h.get(E);if(!b||!M)continue;let c=[...b.values()];(c.some(I=>I[S]===!0)||c.every(I=>I[S]===void 0)&&x.config[S])&&(b.size===0?k.dispatch(A({queryCacheKey:E})):M.status!==j&&k.dispatch(f(M)))}})}return g};function an(e){let{reducerPath:n,queryThunk:u,api:f,context:y,getInternalState:A}=e,{apiUid:g}=y,B={invalidateTags:ee(`${n}/invalidateTags`)},k=h=>h.type.startsWith(`${n}/`),S=[Xt,Jt,en,tn,Zt,nn];return{middleware:h=>{let E=!1,M=A(h.dispatch),b={...e,internalState:M,refetchQuery:T,isThisApiSliceAction:k,mwApi:h},c=S.map(s=>s(b)),R=Yt(b),I=rn(b);return s=>d=>{if(!Qt(d))return s(d);E||(E=!0,h.dispatch(f.internalActions.middlewareRegistered(g)));let i={...h,next:s},Q=h.getState(),[D,m]=R(d,i,Q),p;if(D?p=s(d):p=m,h.getState()[n]&&(I(d,i,Q),k(d)||y.hasRehydrationInfo(d)))for(let a of c)a(d,i,Q);return p}},actions:B};function T(h){return e.api.endpoints[h.endpointName].initiate(h.originalArgs,{subscribe:!1,forceRefetch:!0})}}var Xe=Symbol(),ct=({createSelector:e=mt}={})=>({name:Xe,init(n,{baseQuery:u,tagTypes:f,reducerPath:y,serializeQueryArgs:A,keepUnusedDataFor:g,refetchOnMountOrArgChange:B,refetchOnFocus:k,refetchOnReconnect:S,invalidationBehavior:x,onSchemaFailure:T,catchSchemaFailure:h,skipSchemaValidation:E},M){Ot();let b=U=>U;Object.assign(n,{reducerPath:y,endpoints:{},internalActions:{onOnline:oe,onOffline:De,onFocus:ae,onFocusLost:xe},util:{}});let c=zt({serializeQueryArgs:A,reducerPath:y,createSelector:e}),{selectInvalidatedBy:R,selectCachedArgsForQuery:I,buildQuerySelector:s,buildInfiniteQuerySelector:d,buildMutationSelector:i}=c;Z(n.util,{selectInvalidatedBy:R,selectCachedArgsForQuery:I});let{queryThunk:Q,infiniteQueryThunk:D,mutationThunk:m,patchQueryData:p,updateQueryData:a,upsertQueryData:t,prefetch:r,buildMatchThunkActions:o}=Kt({baseQuery:u,reducerPath:y,context:M,api:n,serializeQueryArgs:A,assertTagType:b,selectors:c,onSchemaFailure:T,catchSchemaFailure:h,skipSchemaValidation:E}),{reducer:l,actions:C}=_t({context:M,queryThunk:Q,infiniteQueryThunk:D,mutationThunk:m,serializeQueryArgs:A,reducerPath:y,assertTagType:b,config:{refetchOnFocus:k,refetchOnReconnect:S,refetchOnMountOrArgChange:B,keepUnusedDataFor:g,reducerPath:y,invalidationBehavior:x}});Z(n.util,{patchQueryData:p,updateQueryData:a,upsertQueryData:t,prefetch:r,resetApiState:C.resetApiState,upsertQueryEntries:C.cacheEntriesUpserted}),Z(n.internalActions,C);let w=new WeakMap,O=U=>ce(w,U,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:F,buildInitiateInfiniteQuery:P,buildInitiateMutation:v,getRunningMutationThunk:L,getRunningMutationsThunk:z,getRunningQueriesThunk:J,getRunningQueryThunk:_}=Ut({queryThunk:Q,mutationThunk:m,infiniteQueryThunk:D,api:n,serializeQueryArgs:A,context:M,getInternalState:O});Z(n.util,{getRunningMutationThunk:L,getRunningMutationsThunk:z,getRunningQueryThunk:_,getRunningQueriesThunk:J});let{middleware:V,actions:H}=an({reducerPath:y,context:M,queryThunk:Q,mutationThunk:m,infiniteQueryThunk:D,api:n,assertTagType:b,selectors:c,getRunningQueryThunk:_,getInternalState:O});return Z(n.util,H),Z(n,{reducer:l,middleware:V}),{name:Xe,injectEndpoint(U,q){let K=n,N=K.endpoints[U]??={};le(q)&&Z(N,{name:U,select:s(U,q),initiate:F(U,q)},o(Q,U)),wt(q)&&Z(N,{name:U,select:i(),initiate:v(U)},o(m,U)),fe(q)&&Z(N,{name:U,select:d(U,q),initiate:P(U,q)},o(Q,U))}}}});var In=dt(ct());export{Pe as NamedSchemaError,ft as QueryStatus,En as _NEVER,dt as buildCreateApi,_e as copyWithStructuralSharing,ct as coreModule,Xe as coreModuleName,In as createApi,Ze as defaultSerializeQueryArgs,bn as fakeBaseQuery,ln as fetchBaseQuery,gn as retry,Rn as setupListeners,Ge as skipToken};
+//# sourceMappingURL=rtk-query.browser.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/query/core/apiState.ts","../../src/query/core/rtkImports.ts","../../src/query/utils/copyWithStructuralSharing.ts","../../src/query/utils/filterMap.ts","../../src/query/utils/isAbsoluteUrl.ts","../../src/query/utils/isDocumentVisible.ts","../../src/query/utils/isNotNullish.ts","../../src/query/utils/isOnline.ts","../../src/query/utils/joinUrls.ts","../../src/query/utils/getOrInsert.ts","../../src/query/utils/signals.ts","../../src/query/fetchBaseQuery.ts","../../src/query/HandledError.ts","../../src/query/retry.ts","../../src/query/core/setupListeners.ts","../../src/query/endpointDefinitions.ts","../../src/query/utils/immerImports.ts","../../src/query/core/buildInitiate.ts","../../src/tsHelpers.ts","../../src/query/apiTypes.ts","../../src/query/standardSchema.ts","../../src/query/core/buildThunks.ts","../../src/query/utils/getCurrent.ts","../../src/query/core/buildSlice.ts","../../src/query/core/buildSelectors.ts","../../src/query/createApi.ts","../../src/query/defaultSerializeQueryArgs.ts","../../src/query/fakeBaseQuery.ts","../../src/query/tsHelpers.ts","../../src/query/core/buildMiddleware/batchActions.ts","../../src/query/core/buildMiddleware/cacheCollection.ts","../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../src/query/core/buildMiddleware/devMiddleware.ts","../../src/query/core/buildMiddleware/invalidationByTags.ts","../../src/query/core/buildMiddleware/polling.ts","../../src/query/core/buildMiddleware/queryLifecycle.ts","../../src/query/core/buildMiddleware/windowEventHandling.ts","../../src/query/core/buildMiddleware/index.ts","../../src/query/core/module.ts","../../src/query/core/index.ts"],"sourcesContent":["import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, FullTagDescription, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFromAnyQuery, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n  _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n  queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n  requestId: string;\n  fixedCacheKey?: string;\n} | {\n  requestId?: string;\n  fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number;\n  refetchOnReconnect: boolean;\n  refetchOnFocus: boolean;\n};\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam;\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (lastPage: DataType, allPages: Array<DataType>, lastPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>;\n  pageParams: Array<PageParam>;\n};\n\n// NOTE: DO NOT import and use this for runtime comparisons internally,\n// except in the RTKQ React package. Use the string versions just below this.\n// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated\n// constants like \"initialized\":\n// https://github.com/evanw/esbuild/releases/tag/v0.14.7\n// We still have to use this in the React package since we don't publicly export\n// the string constants below.\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\n\n// Use these string constants for runtime comparisons internally\nexport const STATUS_UNINITIALIZED = QueryStatus.uninitialized;\nexport const STATUS_PENDING = QueryStatus.pending;\nexport const STATUS_FULFILLED = QueryStatus.fulfilled;\nexport const STATUS_REJECTED = QueryStatus.rejected;\nexport type RequestStatusFlags = {\n  status: QueryStatus.uninitialized;\n  isUninitialized: true;\n  isLoading: false;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.pending;\n  isUninitialized: false;\n  isLoading: true;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.fulfilled;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: true;\n  isError: false;\n} | {\n  status: QueryStatus.rejected;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: false;\n  isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === STATUS_UNINITIALIZED,\n    isLoading: status === STATUS_PENDING,\n    isSuccess: status === STATUS_FULFILLED,\n    isError: status === STATUS_REJECTED\n  } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\nexport type SubscribersInternal = Map<string, SubscriptionOptions>;\nexport type Subscribers = {\n  [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>;\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string;\n  /**\n   * The received data from the query\n   */\n  data?: DataType;\n  /**\n   * The received error if applicable\n   */\n  error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string;\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number;\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n  error: undefined;\n}) | ({\n  status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n  status: QueryStatus.uninitialized;\n  originalArgs?: undefined;\n  data?: undefined;\n  error?: undefined;\n  requestId?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n  direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = {\n  requestId: string;\n  data?: ResultTypeFrom<D>;\n  error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  endpointName: string;\n  startedTimeStamp: number;\n  fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = (({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n  error: undefined;\n}) | (({\n  status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n  data?: undefined;\n}) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n  requestId?: undefined;\n  status: QueryStatus.uninitialized;\n  data?: undefined;\n  error?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n  queries: QueryState<D>;\n  mutations: MutationState<D>;\n  provided: InvalidationState<E>;\n  subscriptions: SubscriptionState;\n  config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = {\n  tags: { [_ in TagTypes]: {\n    [id: string]: Array<QueryCacheKey>;\n    [id: number]: Array<QueryCacheKey>;\n  } };\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;\n};\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionInternalState = Map<string, SubscribersInternal>;\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath;\n  online: boolean;\n  focused: boolean;\n  middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number;\n  invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from '@reduxjs/toolkit';","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n    return newObj;\n  }\n  const newKeys = Object.keys(newObj);\n  const oldKeys = Object.keys(oldObj);\n  let isSameObject = newKeys.length === oldKeys.length;\n  const mergeObj: any = Array.isArray(newObj) ? [] : {};\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n  }\n  return isSameObject ? oldObj : mergeObj;\n}","// Preserve type guard predicate behavior when passing to mapper\nexport 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[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[] {\n  return array.reduce<(U | U[])[]>((acc, item, i) => {\n    if (predicate(item as any, i)) {\n      acc.push(mapper(item as any, i));\n    }\n    return acc;\n  }, []).flat() as U[];\n}","/**\n * If either :// or // is present consider it to be an absolute url\n *\n * @param url string\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url);\n}","/**\n * Assumes true for a non-browser env, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true;\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null;\n}\nexport function filterNullishValues<T>(map?: Map<any, T>) {\n  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[];\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n  if (!base) {\n    return url!;\n  }\n  if (!url) {\n    return base;\n  }\n  if (isAbsoluteUrl(url)) {\n    return url;\n  }\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n  base = withoutTrailingSlash(base);\n  url = withoutLeadingSlash(url);\n  return `${base}${delimiter}${url}`;\n}","// Duplicate some of the utils in `/src/utils` to ensure\n// we don't end up dragging in larger chunks of the RTK core\n// into the RTKQ bundle\n\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport const createNewMap = () => new Map();","// AbortSignal.timeout() is currently baseline 2024\nexport const timeoutSignal = (milliseconds: number) => {\n  const abortController = new AbortController();\n  setTimeout(() => {\n    const message = 'signal timed out';\n    const name = 'TimeoutError';\n    abortController.abort(\n    // some environments (React Native, Node) don't have DOMException\n    typeof DOMException !== 'undefined' ? new DOMException(message, name) : Object.assign(new Error(message), {\n      name\n    }));\n  }, milliseconds);\n  return abortController.signal;\n};\n\n// AbortSignal.any() is currently baseline 2024\nexport const anySignal = (...signals: AbortSignal[]) => {\n  // if any are already aborted, return an already aborted signal\n  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);\n\n  // otherwise, create a new signal that aborts when any of the given signals abort\n  const abortController = new AbortController();\n  for (const signal of signals) {\n    signal.addEventListener('abort', () => abortController.abort(signal.reason), {\n      signal: abortController.signal,\n      once: true\n    });\n  }\n  return abortController.signal;\n};","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nimport { anySignal, timeoutSignal } from './utils/signals';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n  headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n  url: string;\n  params?: Record<string, any>;\n  body?: any;\n  responseHandler?: ResponseHandler;\n  validateStatus?: (response: Response, body: any) => boolean;\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n  /**\n   * * `number`:\n   *   HTTP status code\n   */\n  status: number;\n  data: unknown;\n} | {\n  /**\n   * * `\"FETCH_ERROR\"`:\n   *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n   **/\n  status: 'FETCH_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"PARSING_ERROR\"`:\n   *   An error happened during parsing.\n   *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n   *   or an error occurred while executing a custom `responseHandler`.\n   **/\n  status: 'PARSING_ERROR';\n  originalStatus: number;\n  data: string;\n  error: string;\n} | {\n  /**\n   * * `\"TIMEOUT_ERROR\"`:\n   *   Request timed out\n   **/\n  status: 'TIMEOUT_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"CUSTOM_ERROR\"`:\n   *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n   **/\n  status: 'CUSTOM_ERROR';\n  data?: unknown;\n  error: string;\n};\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj;\n  }\n  const copy: Record<string, any> = {\n    ...obj\n  };\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k];\n  }\n  return copy;\n}\n\n// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\nconst isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string;\n  prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n    arg: string | FetchArgs;\n    extraOptions: unknown;\n  }) => MaybePromise<Headers | void>;\n  fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n  paramsSerializer?: (params: Record<string, any>) => string;\n  /**\n   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean;\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string;\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n  request: Request;\n  response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = x => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n  }\n  return async (arg, api, extraOptions) => {\n    const {\n      getState,\n      extra,\n      endpoint,\n      forced,\n      type\n    } = api;\n    let meta: FetchBaseQueryMeta | undefined;\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? 'json' as const,\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? {\n      url: arg\n    } : arg;\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,\n      ...rest\n    };\n    headers = new Headers(stripUndefined(headers));\n    config.headers = (await prepareHeaders(headers, {\n      getState,\n      arg,\n      extra,\n      endpoint,\n      forced,\n      type,\n      extraOptions\n    })) || headers;\n    const bodyIsJsonifiable = isJsonifiable(config.body);\n\n    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically\n    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)\n    if (config.body != null && !bodyIsJsonifiable && typeof config.body !== 'string') {\n      config.headers.delete('content-type');\n    }\n    if (!config.headers.has('content-type') && bodyIsJsonifiable) {\n      config.headers.set('content-type', jsonContentType);\n    }\n    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer);\n    }\n\n    // Set Accept header based on responseHandler if not already set\n    if (!config.headers.has('accept')) {\n      if (responseHandler === 'json') {\n        config.headers.set('accept', 'application/json');\n      } else if (responseHandler === 'text') {\n        config.headers.set('accept', 'text/plain, text/html, */*');\n      }\n      // For 'content-type' responseHandler, don't set Accept (let server decide)\n    }\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?';\n      const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n      url += divider + query;\n    }\n    url = joinUrls(baseUrl, url);\n    const request = new Request(url, config);\n    const requestClone = new Request(url, config);\n    meta = {\n      request: requestClone\n    };\n    let response;\n    try {\n      response = await fetchFn(request);\n    } catch (e) {\n      return {\n        error: {\n          status: (e instanceof Error || typeof DOMException !== 'undefined' && e instanceof DOMException) && e.name === 'TimeoutError' ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n          error: String(e)\n        },\n        meta\n      };\n    }\n    const responseClone = response.clone();\n    meta.response = responseClone;\n    let resultData: any;\n    let responseText: string = '';\n    try {\n      let handleResponseError;\n      await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n      // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n      // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n      responseClone.text().then(r => responseText = r, () => {})]);\n      if (handleResponseError) throw handleResponseError;\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e)\n        },\n        meta\n      };\n    }\n    return validateStatus(response, resultData) ? {\n      data: resultData,\n      meta\n    } : {\n      error: {\n        status: response.status,\n        data: resultData\n      },\n      meta\n    };\n  };\n  async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response);\n    }\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n    }\n    if (responseHandler === 'json') {\n      const text = await response.text();\n      return text.length ? JSON.parse(text) : null;\n    }\n    return response.text();\n  }\n}","export class HandledError {\n  constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5, signal?: AbortSignal) {\n  const attempts = Math.min(attempt, maxRetries);\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n\n  await new Promise<void>((resolve, reject) => {\n    const timeoutId = setTimeout(() => resolve(), timeout);\n\n    // If signal is provided and gets aborted, clear timeout and reject\n    if (signal) {\n      const abortHandler = () => {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      };\n\n      // Check if already aborted\n      if (signal.aborted) {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      } else {\n        signal.addEventListener('abort', abortHandler, {\n          once: true\n        });\n      }\n    }\n  });\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n  attempt: number;\n  baseQueryApi: BaseQueryApi;\n  extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (attempt: number, maxRetries: number, signal?: AbortSignal) => Promise<void>;\n} & ({\n  /**\n   * How many times the query will be retried (default: 5)\n   */\n  maxRetries?: number;\n  retryCondition?: undefined;\n} | {\n  /**\n   * Callback to determine if a retry should be attempted.\n   * Return `true` for another retry and `false` to quit trying prematurely.\n   */\n  retryCondition?: RetryConditionFunction;\n  maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n  throw Object.assign(new HandledError({\n    error,\n    meta\n  }), {\n    throwImmediately: true\n  });\n}\n\n/**\n * Checks if the abort signal is aborted and fails immediately if so.\n * Used to exit retry loops cleanly when a request is aborted.\n */\nfunction failIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    fail({\n      status: 'CUSTOM_ERROR',\n      error: 'Aborted'\n    });\n  }\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n  const [maxRetries] = possibleMaxRetries.slice(-1);\n  const defaultRetryCondition: RetryConditionFunction = (_, __, {\n    attempt\n  }) => attempt <= maxRetries;\n  const options: {\n    maxRetries: number;\n    backoff: typeof defaultBackoff;\n    retryCondition: typeof defaultRetryCondition;\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions\n  };\n  let retry = 0;\n  while (true) {\n    // Check if aborted before each attempt\n    failIfAborted(api.signal);\n    try {\n      const result = await baseQuery(args, api, extraOptions);\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result);\n      }\n      return result;\n    } catch (e: any) {\n      retry++;\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value;\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e;\n      }\n      if (e instanceof HandledError) {\n        if (!options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n          attempt: retry,\n          baseQueryApi: api,\n          extraOptions\n        })) {\n          return e.value; // Max retries for expected error\n        }\n      } else {\n        // For unexpected errors, respect maxRetries\n        if (retry > options.maxRetries) {\n          // Return the error as a proper error response instead of throwing\n          return {\n            error: e\n          };\n        }\n      }\n\n      // Check if aborted before backoff\n      failIfAborted(api.signal);\n      try {\n        await options.backoff(retry, options.maxRetries, api.signal);\n      } catch (backoffError) {\n        // If backoff was aborted, exit the retry loop\n        failIfAborted(api.signal);\n        // Otherwise, rethrow the backoff error\n        throw backoffError;\n      }\n    }\n  }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n  fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const INTERNAL_PREFIX = '__rtkq/';\nconst ONLINE = 'online';\nconst OFFLINE = 'offline';\nconst FOCUS = 'focus';\nconst FOCUSED = 'focused';\nconst VISIBILITYCHANGE = 'visibilitychange';\nexport const onFocus = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${FOCUSED}`);\nexport const onFocusLost = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);\nexport const onOnline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${ONLINE}`);\nexport const onOffline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${OFFLINE}`);\nconst actions = {\n  onFocus,\n  onFocusLost,\n  onOnline,\n  onOffline\n};\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n}) => () => void) {\n  function defaultHandler() {\n    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map(action => () => dispatch(action()));\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus();\n      } else {\n        handleFocusLost();\n      }\n    };\n    let unsubscribe = () => {\n      initialized = false;\n    };\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        const handlers = {\n          [FOCUS]: handleFocus,\n          [VISIBILITYCHANGE]: handleVisibilityChange,\n          [ONLINE]: handleOnline,\n          [OFFLINE]: handleOffline\n        };\n        function updateListeners(add: boolean) {\n          Object.entries(handlers).forEach(([event, handler]) => {\n            if (add) {\n              window.addEventListener(event, handler, false);\n            } else {\n              window.removeEventListener(event, handler);\n            }\n          });\n        }\n        // Handle focus events\n        updateListeners(true);\n        initialized = true;\n        unsubscribe = () => {\n          updateListeners(false);\n          initialized = false;\n        };\n      }\n    }\n    return unsubscribe;\n  }\n  return customHandler ? customHandler(dispatch, actions) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from 'immer';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { ENDPOINT_QUERY, isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { filterNullishValues } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n  [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\ntype RefetchOptions = {\n  refetchCachedPages?: boolean;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection;\n  param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>, InfiniteQueryArgFrom<D>>>, 'initialPageParam' | 'refetchCachedPages'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n  requestId: string;\n  subscriptionOptions: SubscriptionOptions | undefined;\n  abort(): void;\n  unsubscribe(): void;\n  updateSubscriptionOptions(options: SubscriptionOptions): void;\n  queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n  arg: any;\n  unwrap(): Promise<any>;\n  refetch(options?: RefetchOptions): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: QueryArgFrom<D>;\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: InfiniteQueryArgFrom<D>;\n  unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n  refetch(options?: Pick<StartInfiniteQueryActionCreatorOptions<D>, 'refetchCachedPages'>): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n  fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n  data: ResultTypeFrom<D>;\n  error?: undefined;\n} | {\n  data?: undefined;\n  error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string;\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>;\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean;\n    fixedCacheKey?: string;\n  };\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string;\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void;\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void;\n};\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context,\n  getInternalState\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  api: Api<any, EndpointDefinitions, any, any>;\n  context: ApiContext<EndpointDefinitions>;\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState;\n}) {\n  const getRunningQueries = (dispatch: Dispatch) => getInternalState(dispatch)?.runningQueries;\n  const getRunningMutations = (dispatch: Dispatch) => getInternalState(dispatch)?.runningMutations;\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions\n  } = api.internalActions;\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk\n  };\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      return getRunningQueries(dispatch)?.get(queryCacheKey) as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningMutationThunk(\n  /**\n   * this is only here to allow TS to infer the result type by input value\n   * we could use it to validate the result, but it's probably not necessary\n   */\n  _endpointName: string, fixedCacheKeyOrRequestId: string) {\n    return (dispatch: Dispatch) => {\n      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as MutationActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningQueries(dispatch));\n  }\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningMutations(dispatch));\n  }\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return;\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      (middlewareWarning as any).triggered = true;\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n        // Otherwise, must not have been added\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n      }\n    }\n  }\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n    const queryAction: AnyQueryActionCreator<any> = (arg, {\n      subscribe = true,\n      forceRefetch,\n      subscriptionOptions,\n      [forceQueryFnSymbol]: forceQueryFn,\n      ...rest\n    } = {}) => (dispatch, getState) => {\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName\n      });\n      let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n      const commonThunkArgs = {\n        ...rest,\n        type: ENDPOINT_QUERY as 'query',\n        subscribe,\n        forceRefetch: forceRefetch,\n        subscriptionOptions,\n        endpointName,\n        originalArgs: arg,\n        queryCacheKey,\n        [forceQueryFnSymbol]: forceQueryFn\n      };\n      if (isQueryDefinition(endpointDefinition)) {\n        thunk = queryThunk(commonThunkArgs);\n      } else {\n        const {\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam' | 'refetchCachedPages'>;\n        thunk = infiniteQueryThunk({\n          ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n          // Supply these even if undefined. This helps with a field existence\n          // check over in `buildSlice.ts`\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        });\n      }\n      const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n      const thunkResult = dispatch(thunk);\n      const stateAfter = selector(getState());\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort\n      } = thunkResult;\n      const skippedSynchronously = stateAfter.requestId !== requestId;\n      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);\n      const selectFromState = () => selector(getState());\n      const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n      // a query has been forced (upsertQueryData)\n      // -> we want to resolve it once data has been written with the data that will be written\n      thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n      // a query has been skipped due to a condition and we do not have any currently running query\n      // -> we want to resolve it immediately with the current data\n      Promise.resolve(stateAfter) :\n      // query just started or one is already in flight\n      // -> wait for the running query, then resolve with data from after that\n      Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n        arg,\n        requestId,\n        subscriptionOptions,\n        queryCacheKey,\n        abort,\n        async unwrap() {\n          const result = await statePromise;\n          if (result.isError) {\n            throw result.error;\n          }\n          return result.data;\n        },\n        refetch: (options?: RefetchOptions) => dispatch(queryAction(arg, {\n          subscribe: false,\n          forceRefetch: true,\n          ...options\n        })),\n        unsubscribe() {\n          if (subscribe) dispatch(unsubscribeQueryResult({\n            queryCacheKey,\n            requestId\n          }));\n        },\n        updateSubscriptionOptions(options: SubscriptionOptions) {\n          statePromise.subscriptionOptions = options;\n          dispatch(updateSubscriptionOptions({\n            endpointName,\n            requestId,\n            queryCacheKey,\n            options\n          }));\n        }\n      });\n      if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n        const runningQueries = getRunningQueries(dispatch)!;\n        runningQueries.set(queryCacheKey, statePromise);\n        statePromise.then(() => {\n          runningQueries.delete(queryCacheKey);\n        });\n      }\n      return statePromise;\n    };\n    return queryAction;\n  }\n  function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return queryAction;\n  }\n  function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return infiniteQueryAction;\n  }\n  function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n    return (arg, {\n      track = true,\n      fixedCacheKey\n    } = {}) => (dispatch, getState) => {\n      const thunk = mutationThunk({\n        type: 'mutation',\n        endpointName,\n        originalArgs: arg,\n        track,\n        fixedCacheKey\n      });\n      const thunkResult = dispatch(thunk);\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort,\n        unwrap\n      } = thunkResult;\n      const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n        data\n      })), error => ({\n        error\n      }));\n      const reset = () => {\n        dispatch(removeMutationResult({\n          requestId,\n          fixedCacheKey\n        }));\n      };\n      const ret = Object.assign(returnValuePromise, {\n        arg: thunkResult.arg,\n        requestId,\n        abort,\n        unwrap,\n        reset\n      });\n      const runningMutations = getRunningMutations(dispatch)!;\n      runningMutations.set(requestId, ret);\n      ret.then(() => {\n        runningMutations.delete(requestId);\n      });\n      if (fixedCacheKey) {\n        runningMutations.set(fixedCacheKey, ret);\n        ret.then(() => {\n          if (runningMutations.get(fixedCacheKey) === ret) {\n            runningMutations.delete(fixedCacheKey);\n          }\n        });\n      }\n      return ret;\n    };\n  }\n}","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn } from './baseQueryTypes';\nimport type { CombinedState, CoreModule, QueryKeys } from './core';\nimport type { ApiModules } from './core/module';\nimport type { CreateApiOptions } from './createApi';\nimport type { EndpointBuilder, EndpointDefinition, EndpointDefinitions, UpdateDefinitions } from './endpointDefinitions';\nimport type { NoInfer, UnionToIntersection, WithRequiredProp } from './tsHelpers';\nexport type ModuleName = keyof ApiModules<any, any, any, any>;\nexport type Module<Name extends ModuleName> = {\n  name: Name;\n  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>): {\n    injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;\n  };\n};\nexport interface ApiContext<Definitions extends EndpointDefinitions> {\n  apiUid: string;\n  endpointDefinitions: Definitions;\n  batch(cb: () => void): void;\n  extractRehydrationInfo: (action: UnknownAction) => CombinedState<any, any, any> | undefined;\n  hasRehydrationInfo: (action: UnknownAction) => boolean;\n}\nexport const getEndpointDefinition = <Definitions extends EndpointDefinitions, EndpointName extends keyof Definitions>(context: ApiContext<Definitions>, endpointName: EndpointName) => context.endpointDefinitions[endpointName];\nexport 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]> & {\n  /**\n   * 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.\n   */\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\n    endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;\n    /**\n     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n     *\n     * If set to `true`, will override existing endpoints with the new definition.\n     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n     */\n    overrideExisting?: boolean | 'throw';\n  }): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;\n  /**\n   *A function to enhance a generated API with additional information. Useful with code-generation.\n   */\n  enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {\n    addTagTypes?: readonly NewTagTypes[];\n    endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? { [K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void) } : never;\n  }): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;\n};","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { SchemaError } from '@standard-schema/utils';\nimport type { SchemaType } from './endpointDefinitions';\nexport class NamedSchemaError extends SchemaError {\n  constructor(issues: readonly StandardSchemaV1.Issue[], public readonly value: any, public readonly schemaName: `${SchemaType}Schema`, public readonly _bqMeta: any) {\n    super(issues);\n  }\n}\nexport const shouldSkip = (skipSchemaValidation: boolean | SchemaType[] | undefined, schemaName: SchemaType) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(schema: Schema, data: unknown, schemaName: `${SchemaType}Schema`, bqMeta: any): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data);\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);\n  }\n  return result.value;\n}","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from '../utils/immerImports';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultDescription, ResultTypeFrom, SchemaFailureConverter, SchemaFailureHandler, SchemaFailureInfo, SchemaType } from '../endpointDefinitions';\nimport { calculateProvidedBy, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nimport { parseWithSchema, NamedSchemaError, shouldSkip } from '../standardSchema';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>;\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n  type: 'query';\n  originalArgs: unknown;\n  endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n  type: `query`;\n  originalArgs: unknown;\n  endpointName: string;\n  param: unknown;\n  direction?: InfiniteQueryDirection;\n  refetchCachedPages?: boolean;\n};\ntype MutationThunkArg = {\n  type: 'mutation';\n  originalArgs: unknown;\n  endpointName: string;\n  track?: boolean;\n  fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n  pendingMeta: {\n    startedTimeStamp: number;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  fulfilledMeta: {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  rejectedMeta: {\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;\nexport type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;\nexport type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;\nexport type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;\nexport type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[];\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[];\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n  [SHOULD_AUTOBATCH]: true;\n} => {\n  return {\n    ...arg,\n    [SHOULD_AUTOBATCH]: true\n  };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n  reducerPath,\n  baseQuery,\n  context: {\n    endpointDefinitions\n  },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation\n}: {\n  baseQuery: BaseQuery;\n  reducerPath: ReducerPath;\n  context: ApiContext<Definitions>;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  api: Api<BaseQuery, Definitions, ReducerPath, any>;\n  assertTagType: AssertTagTypes;\n  selectors: AllSelectors;\n  onSchemaFailure: SchemaFailureHandler | undefined;\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined;\n  skipSchemaValidation: boolean | SchemaType[] | undefined;\n}) {\n  type State = RootState<any, string, ReducerPath>;\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n    const endpointDefinition = endpointDefinitions[endpointName];\n    const queryCacheKey = serializeQueryArgs({\n      queryArgs: arg,\n      endpointDefinition,\n      endpointName\n    });\n    dispatch(api.internalActions.queryResultPatched({\n      queryCacheKey,\n      patches\n    }));\n    if (!updateProvided) {\n      return;\n    }\n    const newValue = api.endpoints[endpointName].select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n    dispatch(api.internalActions.updateProvidedBy([{\n      queryCacheKey,\n      providedTags\n    }]));\n  };\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items];\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n  }\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item];\n    return max && newItems.length > max ? newItems.slice(1) : newItems;\n  }\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n    const endpointDefinition = api.endpoints[endpointName];\n    const currentState = endpointDefinition.select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const ret: PatchCollection = {\n      patches: [],\n      inversePatches: [],\n      undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n    };\n    if (currentState.status === STATUS_UNINITIALIZED) {\n      return ret;\n    }\n    let newValue;\n    if ('data' in currentState) {\n      if (isDraftable(currentState.data)) {\n        const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n        ret.patches.push(...patches);\n        ret.inversePatches.push(...inversePatches);\n        newValue = value;\n      } else {\n        newValue = updateRecipe(currentState.data);\n        ret.patches.push({\n          op: 'replace',\n          path: [],\n          value: newValue\n        });\n        ret.inversePatches.push({\n          op: 'replace',\n          path: [],\n          value: currentState.data\n        });\n      }\n    }\n    if (ret.patches.length === 0) {\n      return ret;\n    }\n    dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n    return ret;\n  };\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n    type EndpointName = typeof endpointName;\n    const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n      subscribe: false,\n      forceRefetch: true,\n      [forceQueryFnSymbol]: () => ({\n        data: value\n      })\n    })) as UpsertThunkResult<Definitions, EndpointName>;\n    return res;\n  };\n  const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n  };\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }> = async (arg, {\n    signal,\n    abort,\n    rejectWithValue,\n    fulfillWithValue,\n    dispatch,\n    getState,\n    extra\n  }) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName];\n    const {\n      metaSchema,\n      skipSchemaValidation = globalSkipSchemaValidation\n    } = endpointDefinition;\n    const isQuery = arg.type === ENDPOINT_QUERY;\n    try {\n      let transformResponse: TransformCallback = defaultTransformResponse;\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n      };\n      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined;\n      let finalQueryReturnValue: QueryReturnValue;\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({\n            data\n          });\n        }\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param\n        };\n        const pageResponse = await executeRequest(finalQueryArg);\n        const addTo = previous ? addToStart : addToEnd;\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages)\n          },\n          meta: pageResponse.meta\n        };\n      };\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n        let result: QueryReturnValue;\n        const {\n          extraOptions,\n          argSchema,\n          rawResponseSchema,\n          responseSchema\n        } = endpointDefinition;\n        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {\n          finalQueryArg = await parseWithSchema(argSchema, finalQueryArg, 'argSchema', {} // we don't have a meta yet, so we can't pass it\n          );\n        }\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn();\n        } else if (endpointDefinition.query) {\n          // We should only run `transformResponse` when the endpoint has a `query` method,\n          // and we're not doing an `upsertQueryData`.\n          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n          result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n        } else {\n          result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n          let err: undefined | string;\n          if (!result) {\n            err = `${what} did not return anything.`;\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`;\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`;\n                break;\n              }\n            }\n          }\n          if (err) {\n            console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`, result);\n          }\n        }\n        if (result.error) throw new HandledError(result.error, result.meta);\n        let {\n          data\n        } = result;\n        if (rawResponseSchema && !shouldSkip(skipSchemaValidation, 'rawResponse')) {\n          data = await parseWithSchema(rawResponseSchema, result.data, 'rawResponseSchema', result.meta);\n        }\n        let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);\n        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {\n          transformedResponse = await parseWithSchema(responseSchema, transformedResponse, 'responseSchema', result.meta);\n        }\n        return {\n          ...result,\n          data: transformedResponse\n        };\n      }\n      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const {\n          infiniteQueryOptions\n        } = endpointDefinition;\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const {\n          maxPages = Infinity\n        } = infiniteQueryOptions;\n\n        // Priority: per-call override > endpoint config > default (true)\n        const refetchCachedPages = (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;\n        let result: QueryReturnValue;\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = {\n          pages: [],\n          pageParams: []\n        };\n        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch =\n        // arg.forceRefetch\n        isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n        const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward';\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n          const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);\n          result = await fetchPage(existingData, param, maxPages, previous);\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const {\n            initialPageParam = infiniteQueryOptions.initialPageParam\n          } = arg as InfiniteQueryThunkArg<any>;\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? [];\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n          const totalPages = cachedPageParams.length;\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages);\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n            } as QueryReturnValue;\n          }\n          if (refetchCachedPages) {\n            // Fetch remaining pages\n            for (let i = 1; i < totalPages; i++) {\n              const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>, arg.originalArgs);\n              result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n            }\n          }\n        }\n        finalQueryReturnValue = result;\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs);\n      }\n      if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta') && finalQueryReturnValue.meta) {\n        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, 'metaSchema', finalQueryReturnValue.meta);\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n        fulfilledTimeStamp: Date.now(),\n        baseQueryMeta: finalQueryReturnValue.meta\n      }));\n    } catch (error) {\n      let caughtError = error;\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n        const {\n          rawErrorResponseSchema,\n          errorResponseSchema\n        } = endpointDefinition;\n        let {\n          value,\n          meta\n        } = caughtError;\n        try {\n          if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, 'rawErrorResponse')) {\n            value = await parseWithSchema(rawErrorResponseSchema, value, 'rawErrorResponseSchema', meta);\n          }\n          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta);\n          }\n          let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);\n          if (errorResponseSchema && !shouldSkip(skipSchemaValidation, 'errorResponse')) {\n            transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, 'errorResponseSchema', meta);\n          }\n          return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({\n            baseQueryMeta: meta\n          }));\n        } catch (e) {\n          caughtError = e;\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n          };\n          endpointDefinition.onSchemaFailure?.(caughtError, info);\n          onSchemaFailure?.(caughtError, info);\n          const {\n            catchSchemaFailure = globalCatchSchemaFailure\n          } = endpointDefinition;\n          if (catchSchemaFailure) {\n            return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({\n              baseQueryMeta: caughtError._bqMeta\n            }));\n          }\n        }\n      } catch (e) {\n        caughtError = e;\n      }\n      if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n        console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, caughtError);\n      } else {\n        console.error(caughtError);\n      }\n      throw caughtError;\n    }\n  };\n  function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n    const fulfilledVal = requestState?.fulfilledTimeStamp;\n    const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n    }\n    return false;\n  }\n  const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n    const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n      state: RootState<any, string, ReducerPath>;\n    }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({\n        arg\n      }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName];\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n            direction: (arg as InfiniteQueryThunkArg<any>).direction\n          } : {})\n        });\n      },\n      condition(queryThunkArg, {\n        getState\n      }) {\n        const state = getState();\n        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n        const fulfilledVal = requestState?.fulfilledTimeStamp;\n        const currentArg = queryThunkArg.originalArgs;\n        const previousArg = requestState?.originalArgs;\n        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true;\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false;\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true;\n        }\n        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n          currentArg,\n          previousArg,\n          endpointState: requestState,\n          state\n        })) {\n          return true;\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false;\n        }\n        return true;\n      },\n      dispatchConditionRejection: true\n    });\n    return generatedQueryThunk;\n  };\n  const queryThunk = createQueryThunk<QueryThunkArg>();\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n  const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({\n        startedTimeStamp: Date.now()\n      });\n    }\n  });\n  const hasTheForce = (options: any): options is {\n    force: boolean;\n  } => 'force' in options;\n  const hasMaxAge = (options: any): options is {\n    ifOlderThan: false | number;\n  } => 'ifOlderThan' in options;\n  const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions = {}): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n    const force = hasTheForce(options) && options.force;\n    const maxAge = hasMaxAge(options) && options.ifOlderThan;\n    const queryAction = (force: boolean = true) => {\n      const options: StartQueryActionCreatorOptions = {\n        forceRefetch: force,\n        subscribe: false\n      };\n      return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n    };\n    const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n    if (force) {\n      dispatch(queryAction());\n    } else if (maxAge) {\n      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n      if (!lastFulfilledTs) {\n        dispatch(queryAction());\n        return;\n      }\n      const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n      if (shouldRetrigger) {\n        dispatch(queryAction());\n      }\n    } else {\n      // If prefetching with no options, just let it try\n      dispatch(queryAction(false));\n    }\n  };\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n  }\n  function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n    } as Matchers<Thunk, any>;\n  }\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions\n  };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  const lastIndex = pages.length - 1;\n  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n  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);\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../utils/immerImports';\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}","import type { PayloadAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { STATUS_FULFILLED, STATUS_PENDING, QueryStatus, STATUS_REJECTED, STATUS_UNINITIALIZED } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { ENDPOINT_QUERY, isInfiniteQueryDefinition, type AssertTagTypes, type EndpointDefinitions, type FullTagDescription, type QueryDefinition } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { applyPatches, original, isDraft } from '../utils/immerImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport { getCurrent } from '../utils/getCurrent';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n  endpointName: EndpointName;\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string;\n  arg: unknown;\n  value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg;\n  value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n  const substate = state[queryCacheKey];\n  if (substate) {\n    update(substate);\n  }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n} | MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}, update: (substate: MutationSubState<any>) => void) {\n  const substate = state[getMutationCacheKey(id)];\n  if (substate) {\n    update(substate);\n  }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo\n  },\n  assertTagType,\n  config\n}: {\n  reducerPath: string;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  context: ApiContext<EndpointDefinitions>;\n  assertTagType: AssertTagTypes;\n  config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`);\n  function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n    // requestStatus: 'pending'\n  } & {\n    startedTimeStamp: number;\n  }) {\n    draft[arg.queryCacheKey] ??= {\n      status: STATUS_UNINITIALIZED,\n      endpointName: arg.endpointName\n    };\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n      substate.status = STATUS_PENDING;\n      substate.requestId = upserting && substate.requestId ?\n      // for `upsertQuery` **updates**, keep the current `requestId`\n      substate.requestId :\n      // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n      meta.requestId;\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs;\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp;\n      const endpointDefinition = definitions[meta.arg.endpointName];\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;\n        (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n      }\n    });\n  }\n  function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n  } & {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n  }, payload: unknown, upserting: boolean) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n      if (substate.requestId !== meta.requestId && !upserting) return;\n      const {\n        merge\n      } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n      substate.status = STATUS_FULFILLED;\n      if (merge) {\n        if (substate.data !== undefined) {\n          const {\n            fulfilledTimeStamp,\n            arg,\n            baseQueryMeta,\n            requestId\n          } = meta;\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, draftSubstateData => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId\n            });\n          });\n          substate.data = newData;\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload;\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n      }\n      delete substate.error;\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n    });\n  }\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey\n          }\n        }: PayloadAction<QuerySubstateIdentifier>) {\n          delete draft[queryCacheKey];\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n      },\n      cacheEntriesUpserted: {\n        reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n          RTK_autoBatch: boolean;\n          requestId: string;\n          timestamp: number;\n        }>) {\n          for (const entry of action.payload) {\n            const {\n              queryDescription: arg,\n              value\n            } = entry;\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp\n            });\n            writeFulfilledCacheEntry(draft, {\n              arg,\n              requestId: action.meta.requestId,\n              fulfilledTimeStamp: action.meta.timestamp,\n              baseQueryMeta: {}\n            }, value,\n            // We know we're upserting here\n            true);\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n            const {\n              endpointName,\n              arg,\n              value\n            } = entry;\n            const endpointDefinition = definitions[endpointName];\n            const queryDescription: QueryThunkArg = {\n              type: ENDPOINT_QUERY as 'query',\n              endpointName,\n              originalArgs: entry.arg,\n              queryCacheKey: serializeQueryArgs({\n                queryArgs: arg,\n                endpointDefinition,\n                endpointName\n              })\n            };\n            return {\n              queryDescription,\n              value\n            };\n          });\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now()\n            }\n          };\n          return result;\n        }\n      },\n      queryResultPatched: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey,\n            patches\n          }\n        }: PayloadAction<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n            substate.data = applyPatches(substate.data as any, patches.concat());\n          });\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(queryThunk.pending, (draft, {\n        meta,\n        meta: {\n          arg\n        }\n      }) => {\n        const upserting = isUpsertQuery(arg);\n        writePendingCacheEntry(draft, arg, upserting, meta);\n      }).addCase(queryThunk.fulfilled, (draft, {\n        meta,\n        payload\n      }) => {\n        const upserting = isUpsertQuery(meta.arg);\n        writeFulfilledCacheEntry(draft, meta, payload, upserting);\n      }).addCase(queryThunk.rejected, (draft, {\n        meta: {\n          condition,\n          arg,\n          requestId\n        },\n        error,\n        payload\n      }) => {\n        updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n          if (condition) {\n            // request was aborted due to condition (another query already running)\n          } else {\n            // request failed\n            if (substate.requestId !== requestId) return;\n            substate.status = STATUS_REJECTED;\n            substate.error = (payload ?? error) as any;\n          }\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          queries\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(queries)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, {\n          payload\n        }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload);\n          if (cacheKey in draft) {\n            delete draft[cacheKey];\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(mutationThunk.pending, (draft, {\n        meta,\n        meta: {\n          requestId,\n          arg,\n          startedTimeStamp\n        }\n      }) => {\n        if (!arg.track) return;\n        draft[getMutationCacheKey(meta)] = {\n          requestId,\n          status: STATUS_PENDING,\n          endpointName: arg.endpointName,\n          startedTimeStamp\n        };\n      }).addCase(mutationThunk.fulfilled, (draft, {\n        payload,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_FULFILLED;\n          substate.data = payload;\n          substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n        });\n      }).addCase(mutationThunk.rejected, (draft, {\n        payload,\n        error,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_REJECTED;\n          substate.error = (payload ?? error) as any;\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          mutations\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(mutations)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) &&\n          // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n          key !== entry?.requestId) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  type CalculateProvidedByAction = UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>;\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {}\n  };\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(draft, action: PayloadAction<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>) {\n          for (const {\n            queryCacheKey,\n            providedTags\n          } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey);\n            for (const {\n              type,\n              id\n            } of providedTags) {\n              const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] = providedTags as FullTagDescription<string>[];\n          }\n        },\n        prepare: prepareAutoBatched<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n        payload: {\n          queryCacheKey\n        }\n      }) => {\n        removeCacheKeyFromTags(draft, queryCacheKey);\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          provided\n        } = extractRehydrationInfo(action)!;\n        for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {\n          for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n            const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n            for (const queryCacheKey of cacheKeys) {\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n              draft.keys[queryCacheKey] = provided.keys[queryCacheKey];\n            }\n          }\n        }\n      }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n        writeProvidedTagsForQueries(draft, [action]);\n      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {\n        const mockActions: CalculateProvidedByAction[] = action.payload.map(({\n          queryDescription,\n          value\n        }) => {\n          return {\n            type: 'UNKNOWN',\n            payload: value,\n            meta: {\n              requestStatus: 'fulfilled',\n              requestId: 'UNKNOWN',\n              arg: queryDescription\n            }\n          };\n        });\n        writeProvidedTagsForQueries(draft, mockActions);\n      });\n    }\n  });\n  function removeCacheKeyFromTags(draft: InvalidationState<any>, queryCacheKey: QueryCacheKey) {\n    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type;\n      const tagId = tag.id ?? '__internal_without_id';\n      const tagSubscriptions = draft.tags[tagType]?.[tagId];\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(qc => qc !== queryCacheKey);\n      }\n    }\n    delete draft.keys[queryCacheKey];\n  }\n  function writeProvidedTagsForQueries(draft: InvalidationState<string>, actions: CalculateProvidedByAction[]) {\n    const providedByEntries = actions.map(action => {\n      const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n      const {\n        queryCacheKey\n      } = action.meta.arg;\n      return {\n        queryCacheKey,\n        providedTags\n      };\n    });\n    invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(d, a: PayloadAction<{\n        endpointName: string;\n        requestId: string;\n        options: Subscribers[number];\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      unsubscribeQueryResult(d, a: PayloadAction<{\n        requestId: string;\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {}\n    }\n  });\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload);\n        },\n        prepare: prepareAutoBatched<Patch[]>()\n      }\n    }\n  });\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, {\n        payload\n      }: PayloadAction<string>) {\n        state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n      }\n    },\n    extraReducers: builder => {\n      builder.addCase(onOnline, state => {\n        state.online = true;\n      }).addCase(onOffline, state => {\n        state.online = false;\n      }).addCase(onFocus, state => {\n        state.focused = true;\n      }).addCase(onFocusLost, state => {\n        state.focused = false;\n      })\n      // update the state to be a new object to be picked up as a \"state change\"\n      // by redux-persist's `autoMergeLevel2`\n      .addMatcher(hasRehydrationInfo, draft => ({\n        ...draft\n      }));\n    }\n  });\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer\n  });\n  const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState\n  };\n  return {\n    reducer,\n    actions\n  };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { filterMap, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState, QueryStatus } from './apiState';\nimport { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { type AllQueryKeys, getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n  isFetchNextPageError: boolean;\n  isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n  requestId: string | undefined;\n  fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n  status: STATUS_UNINITIALIZED\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  reducerPath: ReducerPath;\n  createSelector: typeof _createSelector;\n}) {\n  type RootState = _RootState<Definitions, string, string>;\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig\n  };\n  function withRequestFlags<T extends {\n    status: QueryStatus;\n  }>(substate: T): T & RequestStatusFlags {\n    return {\n      ...substate,\n      ...getRequestStatusFlags(substate.status)\n    };\n  }\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath];\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state;\n        (selectApiState as any).triggered = true;\n        console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n      }\n    }\n    return state;\n  }\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries;\n  }\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey];\n  }\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations;\n  }\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config;\n  }\n  function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n    status: QueryStatus;\n  }>(substate: T) => T & RequestStatusFlags) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner);\n      }\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n      return createSelector(selectQuerySubstate, combiner);\n    };\n  }\n  function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n  }\n  function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const {\n      infiniteQueryOptions\n    } = endpointDefinition;\n    function withInfiniteQueryResultFlags<T extends {\n      status: QueryStatus;\n    }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status)\n      };\n      const {\n        isLoading,\n        isError,\n        direction\n      } = stateWithRequestFlags;\n      const isForward = direction === 'forward';\n      const isBackward = direction === 'backward';\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward\n      };\n    }\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n  }\n  function buildMutationSelector() {\n    return (id => {\n      let mutationId: string | typeof skipToken;\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken;\n      } else {\n        mutationId = id;\n      }\n      const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n      return createSelector(finalSelectMutationSubstate, withRequestFlags);\n    }) as MutationResultSelectorFactory<any, RootState>;\n  }\n  function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n    endpointName: string;\n    originalArgs: any;\n    queryCacheKey: QueryCacheKey;\n  }> {\n    const apiState = state[reducerPath];\n    const toInvalidate = new Set<QueryCacheKey>();\n    const finalTags = filterMap(tags, isNotNullish, expandTagDescription);\n    for (const tag of finalTags) {\n      const provided = apiState.provided.tags[tag.type];\n      if (!provided) {\n        continue;\n      }\n      let invalidateSubscriptions = (tag.id !== undefined ?\n      // id given: invalidate all queries that provide this type & id\n      provided[tag.id] :\n      // no id: invalidate all queries that provide this type\n      Object.values(provided).flat()) ?? [];\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate);\n      }\n    }\n    return Array.from(toInvalidate.values()).flatMap(queryCacheKey => {\n      const querySubState = apiState.queries[queryCacheKey];\n      return querySubState ? {\n        queryCacheKey,\n        endpointName: querySubState.endpointName!,\n        originalArgs: querySubState.originalArgs\n      } : [];\n    });\n  }\n  function selectCachedArgsForQuery<QueryName extends AllQueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return filterMap(Object.values(selectQueries(state) as QueryState<any>), (entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n      status: QueryStatus.uninitialized;\n    }> => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, entry => entry.originalArgs);\n  }\n  function getHasNextPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data) return false;\n    return getNextPageParam(options, data, queryArg) != null;\n  }\n  function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data || !options.getPreviousPageParam) return false;\n    return getPreviousPageParam(options, data, queryArg) != null;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport { getEndpointDefinition, type Api, type ApiContext, type Module, type ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions, SchemaFailureConverter, SchemaFailureHandler, SchemaType } from './endpointDefinitions';\nimport { DefinitionType, ENDPOINT_INFINITEQUERY, ENDPOINT_MUTATION, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n  /**\n   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery;\n  /**\n   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[];\n  /**\n   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath;\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>;\n  /**\n   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n   */\n  endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n  /**\n   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts'\n   *     })\n   *   }),\n   *   // highlight-start\n   *   keepUnusedDataFor: 5\n   *   // highlight-end\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately';\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (action: UnknownAction, {\n    reducerPath\n  }: {\n    reducerPath: ReducerPath;\n  }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n      reducerPath: (options.reducerPath ?? 'api') as any\n    }));\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n          finalSerializeQueryArgs = queryArgsApi => {\n            const initialResult = endpointSQA(queryArgsApi);\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult;\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult\n              });\n            }\n          };\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs;\n        }\n        return finalSerializeQueryArgs(queryArgsApi);\n      },\n      tagTypes: [...(options.tagTypes || [])]\n    };\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn();\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n    };\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({\n        addTagTypes,\n        endpoints\n      }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;\n              (optionsWithDefaults.tagTypes as any[]).push(eT);\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(getEndpointDefinition(context, endpointName));\n            } else {\n              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);\n            }\n          }\n        }\n        return api;\n      }\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n    const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n    function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: x => ({\n          ...x,\n          type: ENDPOINT_QUERY\n        }) as any,\n        mutation: x => ({\n          ...x,\n          type: ENDPOINT_MUTATION\n        }) as any,\n        infiniteQuery: x => ({\n          ...x,\n          type: ENDPOINT_INFINITEQUERY\n        }) as any\n      });\n      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n            console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          }\n          continue;\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          if (isInfiniteQueryDefinition(definition)) {\n            const {\n              infiniteQueryOptions\n            } = definition;\n            const {\n              maxPages,\n              getPreviousPageParam\n            } = infiniteQueryOptions;\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n              }\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n              }\n            }\n          }\n        }\n        context.endpointDefinitions[endpointName] = definition;\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition);\n        }\n      }\n      return api as any;\n    }\n    return api.injectEndpoints({\n      endpoints: options.endpoints as any\n    });\n  };\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs\n}) => {\n  let serialized = '';\n  const cached = cache?.get(queryArgs);\n  if (typeof cached === 'string') {\n    serialized = cached;\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? {\n        $bigint: value.toString()\n      } : value;\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n        acc[key] = (value as any)[key];\n        return acc;\n      }, {}) : value;\n      return value;\n    });\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified);\n    }\n    serialized = stringified;\n  }\n  return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n  return function () {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n  };\n}","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionInternalState, SubscriptionState } from '../apiState';\nimport { produceWithPatches } from '../../utils/immerImports';\nimport type { Action } from '@reduxjs/toolkit';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n  api,\n  queryThunk,\n  internalState,\n  mwApi\n}) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n  let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n  const {\n    updateSubscriptionOptions,\n    unsubscribeQueryResult\n  } = api.internalActions;\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (currentSubscriptions: SubscriptionInternalState, action: Action) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const {\n        queryCacheKey,\n        requestId,\n        options\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub?.has(requestId)) {\n        sub.set(requestId, options);\n      }\n      return true;\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const {\n        queryCacheKey,\n        requestId\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub) {\n        sub.delete(requestId);\n      }\n      return true;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      currentSubscriptions.delete(action.payload.queryCacheKey);\n      return true;\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: {\n          arg,\n          requestId\n        }\n      } = action;\n      const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n      if (arg.subscribe) {\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n      }\n      return true;\n    }\n    let mutated = false;\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: {\n          condition,\n          arg,\n          requestId\n        }\n      } = action;\n      if (condition && arg.subscribe) {\n        const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n        mutated = true;\n      }\n    }\n    return mutated;\n  };\n  const getSubscriptions = () => internalState.currentSubscriptions;\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions();\n    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);\n    return subscriptionsForQueryArg?.size ?? 0;\n  };\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions();\n    return !!subscriptions?.get(queryCacheKey)?.get(requestId);\n  };\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed\n  };\n  function serializeSubscriptions(currentSubscriptions: SubscriptionInternalState): SubscriptionState {\n    // We now use nested Maps for subscriptions, instead of\n    // plain Records. Stringify this accordingly so we can\n    // convert it to the shape we need for the store.\n    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));\n  }\n  return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);\n    }\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = {};\n      internalState.currentSubscriptions.clear();\n      updateSyncTimer = null;\n      return [true, false];\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors];\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n    let actionShouldContinue = true;\n\n    // HACK Sneak the test-only polling state back out\n    if (process.env.NODE_ENV === 'test' && typeof action.type === 'string' && action.type === `${api.reducerPath}/getPolling`) {\n      return [false, internalState.currentPolls] as any;\n    }\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = serializeSubscriptions(internalState.currentSubscriptions);\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions;\n          updateSyncTimer = null;\n        }, 500);\n      }\n      const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n    }\n    return [actionShouldContinue, false];\n  };\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\n\n/**\n * @example\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => 'posts',\n *       // highlight-start\n *       keepUnusedDataFor: 5\n *       // highlight-end\n *     })\n *   })\n * })\n * ```\n */\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   */\n  keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectConfig\n  },\n  getRunningQueryThunk,\n  mwApi\n}) => {\n  const {\n    removeQueryResult,\n    unsubscribeQueryResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);\n    if (!subscriptions) {\n      return false;\n    }\n    const hasSubscriptions = subscriptions.size > 0;\n    return hasSubscriptions;\n  }\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n  function abortAllPromises<T extends {\n    abort?: () => void;\n  }>(promiseMap: Map<string, T | undefined>): void {\n    for (const promise of promiseMap.values()) {\n      promise?.abort?.();\n    }\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    const state = mwApi.getState();\n    const config = selectConfig(state);\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[];\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n      } else {\n        const {\n          queryCacheKey\n        } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n        queryCacheKeys = [queryCacheKey];\n      }\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n    }\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout);\n        delete currentRemovalTimeouts[key];\n      }\n      abortAllPromises(internalState.runningQueries);\n      abortAllPromises(internalState.runningMutations);\n    }\n    if (context.hasRehydrationInfo(action)) {\n      const {\n        queries\n      } = context.extractRehydrationInfo(action)!;\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n    }\n  };\n  function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n    const state = api.getState();\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey);\n      if (entry?.endpointName) {\n        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config);\n      }\n    }\n  }\n  function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string, api: SubMiddlewareApi, config: ConfigState<string>) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName) as QueryDefinition<any, any, any, any>;\n    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return;\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n      if (currentTimeout) {\n        clearTimeout(currentTimeout);\n      }\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          // Try to abort any running query for this cache key\n          const entry = selectQueryEntry(api.getState(), queryCacheKey);\n          if (entry?.endpointName) {\n            const runningQuery = api.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));\n            runningQuery?.abort();\n          }\n          api.dispatch(removeQueryResult({\n            queryCacheKey\n          }));\n        }\n        delete currentRemovalTimeouts![queryCacheKey];\n      }, finalKeepUnusedDataFor * 1000);\n    }\n  }\n  return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta, BaseQueryResult } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition, DefinitionType } from '../../endpointDefinitions';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nimport { getEndpointDefinition } from '@internal/query/apiTypes';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<{\n    type: DefinitionType.query;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<{\n    type: DefinitionType.mutation;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>;\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>;\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown;\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: MetaType;\n  }, typeof neverResolvedError>;\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectApiState\n  }\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk);\n  const isMutationThunk = isAsyncThunkAction(mutationThunk);\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    valueResolved?(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    cacheEntryRemoved(): void;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const {\n    removeQueryResult,\n    removeMutationResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta\n      });\n      delete lifecycle.valueResolved;\n    }\n  }\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey];\n      lifecycle.cacheEntryRemoved();\n    }\n  }\n  function getActionMetaFields(action: ReturnType<typeof queryThunk.pending> | ReturnType<typeof mutationThunk.pending>) {\n    const {\n      arg,\n      requestId\n    } = action.meta;\n    const {\n      endpointName,\n      originalArgs\n    } = arg;\n    return [endpointName, originalArgs, requestId] as const;\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey;\n    function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    }\n    if (queryThunk.pending.match(action)) {\n      const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);\n    } else if (cacheEntriesUpserted.match(action)) {\n      for (const {\n        queryDescription,\n        value\n      } of action.payload) {\n        const {\n          endpointName,\n          originalArgs,\n          queryCacheKey\n        } = queryDescription;\n        checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n        resolveLifecycleEntry(queryCacheKey, value, {});\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n      if (state) {\n        const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n    } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {\n      removeLifecycleEntry(cacheKey);\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey);\n      }\n    }\n  };\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n    }\n    if (removeQueryResult.match(action)) return action.payload.queryCacheKey;\n    if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n    return '';\n  }\n  function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName);\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n    if (!onCacheEntryAdded) return;\n    const lifecycle = {} as CacheLifecycle;\n    const cacheEntryRemoved = new Promise<void>(resolve => {\n      lifecycle.cacheEntryRemoved = resolve;\n    });\n    const cacheDataLoaded: PromiseWithKnownReason<{\n      data: unknown;\n      meta: unknown;\n    }, typeof neverResolvedError> = Promise.race([new Promise<{\n      data: unknown;\n      meta: unknown;\n    }>(resolve => {\n      lifecycle.valueResolved = resolve;\n    }), cacheEntryRemoved.then(() => {\n      throw neverResolvedError;\n    })]);\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {});\n    lifecycleMap[queryCacheKey] = lifecycle;\n    const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);\n    const extra = mwApi.dispatch((_, __, extra) => extra);\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n      cacheDataLoaded,\n      cacheEntryRemoved\n    };\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch(e => {\n      if (e === neverResolvedError) return;\n      throw e;\n    });\n  }\n  return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: {\n    apiUid\n  },\n  reducerPath\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n      }\n    }\n  };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler } from './types';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: {\n    endpointDefinitions\n  },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));\n  let pendingTagInvalidations: FullTagDescription<string>[] = [];\n  // Track via counter so we can avoid iterating over state every time\n  let pendingRequestCount = 0;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {\n      pendingRequestCount++;\n    }\n    if (isQueryEnd(action)) {\n      pendingRequestCount = Math.max(0, pendingRequestCount - 1);\n    }\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi);\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n    }\n  };\n  function hasPendingRequests() {\n    return pendingRequestCount > 0;\n  }\n  function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n    const rootState = mwApi.getState();\n    const state = rootState[reducerPath];\n    pendingTagInvalidations.push(...newTags);\n    if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests()) {\n      return;\n    }\n    const tags = pendingTagInvalidations;\n    pendingTagInvalidations = [];\n    if (tags.length === 0) return;\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values());\n      for (const {\n        queryCacheKey\n      } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey];\n        const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);\n        if (querySubState) {\n          if (subscriptionSubState.size === 0) {\n            mwApi.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            mwApi.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers, SubscribersInternal } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    currentPolls,\n    currentSubscriptions\n  } = internalState;\n\n  // Batching state for polling updates\n  const pendingPollingUpdates = new Set<string>();\n  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n      schedulePollingUpdate(action.payload.queryCacheKey, mwApi);\n    }\n    if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);\n    }\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n      startNextPoll(action.meta.arg, mwApi);\n    }\n    if (api.util.resetApiState.match(action)) {\n      clearPolls();\n      // Clear any pending updates\n      if (pollingUpdateTimer) {\n        clearTimeout(pollingUpdateTimer);\n        pollingUpdateTimer = null;\n      }\n      pendingPollingUpdates.clear();\n    }\n  };\n  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {\n    pendingPollingUpdates.add(queryCacheKey);\n    if (!pollingUpdateTimer) {\n      pollingUpdateTimer = setTimeout(() => {\n        // Process all pending updates in a single batch\n        for (const key of pendingPollingUpdates) {\n          updatePollingInterval({\n            queryCacheKey: key as any\n          }, api);\n        }\n        pendingPollingUpdates.clear();\n        pollingUpdateTimer = null;\n      }, 0);\n    }\n  }\n  function startNextPoll({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;\n    const {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) return;\n    const currentPoll = currentPolls.get(queryCacheKey);\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout);\n      currentPoll.timeout = undefined;\n    }\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    currentPolls.set(queryCacheKey, {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState));\n        }\n        startNextPoll({\n          queryCacheKey\n        }, api);\n      }, lowestPollingInterval)\n    });\n  }\n  function updatePollingInterval({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {\n      return;\n    }\n    const {\n      lowestPollingInterval\n    } = findLowestPollingInterval(subscriptions);\n\n    // HACK add extra data to track how many times this has been called in tests\n    // yes we're mutating a nonexistent field on a Map here\n    if (process.env.NODE_ENV === 'test') {\n      const updateCounters = (currentPolls as any).pollUpdateCounters ??= {};\n      updateCounters[queryCacheKey] ??= 0;\n      updateCounters[queryCacheKey]++;\n    }\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey);\n      return;\n    }\n    const currentPoll = currentPolls.get(queryCacheKey);\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({\n        queryCacheKey\n      }, api);\n    }\n  }\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls.get(key);\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout);\n    }\n    currentPolls.delete(key);\n  }\n  function clearPolls() {\n    for (const key of currentPolls.keys()) {\n      cleanupPollForKey(key);\n    }\n  }\n  function findLowestPollingInterval(subscribers: SubscribersInternal = new Map()) {\n    let skipPollingIfUnfocused: boolean | undefined = false;\n    let lowestPollingInterval = Number.POSITIVE_INFINITY;\n    for (const entry of subscribers.values()) {\n      if (!!entry.pollingInterval) {\n        lowestPollingInterval = Math.min(entry.pollingInterval!, lowestPollingInterval);\n        skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;\n      }\n    }\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    };\n  }\n  return handler;\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: BaseQueryMeta<BaseQuery>;\n  }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n  error: BaseQueryError<BaseQuery>;\n  /**\n   * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n   */\n  isUnhandledError: false;\n  /**\n   * The `meta` returned by the `baseQuery`\n   */\n  meta: BaseQueryMeta<BaseQuery>;\n} | {\n  error: unknown;\n  meta?: undefined;\n  /**\n   * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n   * There can not be made any assumption about the shape of `error`.\n   */\n  isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * import { messageCreated } from './notificationsSlice\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'))\n   *         try {\n   *           const { data } = await queryFulfilled\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'))\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'))\n   *         }\n   *       }\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk);\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    resolve(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    reject(value: QueryFulfilledRejectionReason<any>): unknown;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: {\n          endpointName,\n          originalArgs\n        }\n      } = action.meta;\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const onQueryStarted = endpointDefinition?.onQueryStarted;\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle;\n        const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n          data: unknown;\n          meta: unknown;\n        }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n          lifecycle.resolve = resolve;\n          lifecycle.reject = reject;\n        });\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {});\n        lifecycleMap[requestId] = lifecycle;\n        const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);\n        const extra = mwApi.dispatch((_, __, extra) => extra);\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n          queryFulfilled\n        };\n        onQueryStarted(originalArgs, lifecycleApi as any);\n      }\n    } else if (isFullfilledThunk(action)) {\n      const {\n        requestId,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta\n      });\n      delete lifecycleMap[requestId];\n    } else if (isRejectedThunk(action)) {\n      const {\n        requestId,\n        rejectedWithValue,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any\n      });\n      delete lifecycleMap[requestId];\n    }\n  };\n  return handler;\n};","import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus');\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect');\n    }\n  };\n  function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n    const state = api.getState()[reducerPath];\n    const queries = state.queries;\n    const subscriptions = internalState.currentSubscriptions;\n    context.batch(() => {\n      for (const queryCacheKey of subscriptions.keys()) {\n        const querySubState = queries[queryCacheKey];\n        const subscriptionSubState = subscriptions.get(queryCacheKey);\n        if (!subscriptionSubState || !querySubState) continue;\n        const values = [...subscriptionSubState.values()];\n        const shouldRefetch = values.some(sub => sub[type] === true) || values.every(sub => sub[type] === undefined) && state.config[type];\n        if (shouldRefetch) {\n          if (subscriptionSubState.size === 0) {\n            api.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            api.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const {\n    reducerPath,\n    queryThunk,\n    api,\n    context,\n    getInternalState\n  } = input;\n  const {\n    apiUid\n  } = context;\n  const actions = {\n    invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n  };\n  const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n  const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n  const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n    let initialized = false;\n    const internalState = getInternalState(mwApi.dispatch);\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction,\n      mwApi\n    };\n    const handlers = handlerBuilders.map(build => build(builderArgs));\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n    const windowEventsHandler = buildWindowEventHandler(builderArgs);\n    return next => {\n      return action => {\n        if (!isAction(action)) {\n          return next(action);\n        }\n        if (!initialized) {\n          initialized = true;\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n        }\n        const mwApiWithNext = {\n          ...mwApi,\n          next\n        };\n        const stateBefore = mwApi.getState();\n        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n        let res: any;\n        if (actionShouldContinue) {\n          res = next(action);\n        } else {\n          res = internalProbeResult;\n        }\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore);\n          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore);\n            }\n          }\n        }\n        return res;\n      };\n    };\n  };\n  return {\n    middleware,\n    actions\n  };\n  function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n    status: QueryStatus.uninitialized;\n  }>) {\n    return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true\n    });\n  }\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Dispatch, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from '../utils/immerImports';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nimport { getOrInsertComputed } from '../utils';\nimport type { CreateSelectorFunction } from 'reselect';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n */\nexport type PrefetchOptions = {\n  ifOlderThan?: false | number;\n} | {\n  force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath;\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions;\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n    /**\n     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'query';\n      }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'infinitequery';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n        type: 'mutation';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n       *\n       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n      /**\n       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n       *\n       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n       *\n       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n       *\n       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n       *\n       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n      /**\n       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n       *\n       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n       *\n       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState'];\n      upsertQueryEntries: UpsertEntries<Definitions>;\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n       *\n       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n       *\n       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n        endpointName: string;\n        originalArgs: any;\n        queryCacheKey: string;\n      }>;\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;\n    };\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never };\n  };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(api, {\n    baseQuery,\n    tagTypes,\n    reducerPath,\n    serializeQueryArgs,\n    keepUnusedDataFor,\n    refetchOnMountOrArgChange,\n    refetchOnFocus,\n    refetchOnReconnect,\n    invalidationBehavior,\n    onSchemaFailure,\n    catchSchemaFailure,\n    skipSchemaValidation\n  }, context) {\n    enablePatches();\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n    const assertTagType: AssertTagTypes = tag => {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n        }\n      }\n      return tag;\n    };\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost\n      },\n      util: {}\n    });\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector\n    });\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector\n    } = selectors;\n    safeAssign(api.util, {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery\n    });\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation\n    });\n    const {\n      reducer,\n      actions: sliceActions\n    } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior\n      }\n    });\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n    });\n    safeAssign(api.internalActions, sliceActions);\n    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>();\n    const getInternalState = (dispatch: Dispatch) => {\n      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({\n        currentSubscriptions: new Map(),\n        currentPolls: new Map(),\n        runningQueries: new Map(),\n        runningMutations: new Map()\n      }));\n      return state;\n    };\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context,\n      getInternalState\n    });\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk\n    });\n    const {\n      middleware,\n      actions: middlewareActions\n    } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors,\n      getRunningQueryThunk,\n      getInternalState\n    });\n    safeAssign(api.util, middlewareActions);\n    safeAssign(api, {\n      reducer: reducer as any,\n      middleware\n    });\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n        const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n        if (isQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildQuerySelector(endpointName, definition),\n            initiate: buildInitiateQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildMutationSelector(),\n            initiate: buildInitiateMutation(endpointName)\n          }, buildMatchThunkActions(mutationThunk, endpointName));\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildInfiniteQuerySelector(endpointName, definition),\n            initiate: buildInitiateInfiniteQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n      }\n    };\n  }\n});","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":"AAkEO,IAAKA,QACVA,EAAA,cAAgB,gBAChBA,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WAJDA,QAAA,IAQCC,EAAuB,gBACvBC,GAAiB,UACjBC,GAAmB,YACnBC,GAAkB,WA0BxB,SAASC,GAAsBC,EAAyC,CAC7E,MAA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CACJ,WAAAG,EACA,QAASC,CACX,EAAIC,GAAgB,CAClB,YAAApD,EACA,QAAAU,EACA,WAAAgB,EACA,cAAAE,EACA,mBAAAD,EACA,IAAA9B,EACA,cAAAe,EACA,UAAAM,EACA,qBAAA8B,EACA,iBAAAT,CACF,CAAC,EACD,OAAAd,EAAW5B,EAAI,KAAMsD,CAAiB,EACtC1B,EAAW5B,EAAK,CACd,QAASsC,EACT,WAAAe,CACF,CAAC,EACM,CACL,KAAMxD,GACN,eAAe2D,EAAcC,EAAY,CACvC,IAAMC,EAAS1D,EACT2D,EAAWD,EAAO,UAAUF,CAAY,IAAM,CAAC,EACjDI,GAAkBH,CAAU,GAC9B7B,EAAW+B,EAAU,CACnB,KAAMH,EACN,OAAQ/B,EAAmB+B,EAAcC,CAAU,EACnD,SAAUZ,EAAmBW,EAAcC,CAAU,CACvD,EAAGrB,EAAuBP,EAAY2B,CAAY,CAAC,EAEjDK,GAAqBJ,CAAU,GACjC7B,EAAW+B,EAAU,CACnB,KAAMH,EACN,OAAQ7B,EAAsB,EAC9B,SAAUoB,EAAsBS,CAAY,CAC9C,EAAGpB,EAAuBL,EAAeyB,CAAY,CAAC,EAEpDM,GAA0BL,CAAU,GACtC7B,EAAW+B,EAAU,CACnB,KAAMH,EACN,OAAQ9B,EAA2B8B,EAAcC,CAAU,EAC3D,SAAUX,EAA2BU,EAAcC,CAAU,CAC/D,EAAGrB,EAAuBP,EAAY2B,CAAY,CAAC,CAEvD,CACF,CACF,CACF,GCniBO,IAAMO,GAA2BC,GAAeC,GAAW,CAAC","names":["QueryStatus","STATUS_UNINITIALIZED","STATUS_PENDING","STATUS_FULFILLED","STATUS_REJECTED","getRequestStatusFlags","status","createAction","createSlice","createSelector","createAsyncThunk","combineReducers","createNextState","isAnyOf","isAllOf","isAction","isPending","isRejected","isFulfilled","isRejectedWithValue","isAsyncThunkAction","prepareAutoBatched","SHOULD_AUTOBATCH","isPlainObject","nanoid","isPlainObject","copyWithStructuralSharing","oldObj","newObj","newKeys","oldKeys","isSameObject","mergeObj","key","filterMap","array","predicate","mapper","acc","item","i","isAbsoluteUrl","url","isDocumentVisible","isNotNullish","v","filterNullishValues","map","isOnline","withoutTrailingSlash","url","withoutLeadingSlash","joinUrls","base","isAbsoluteUrl","delimiter","getOrInsertComputed","map","key","compute","createNewMap","timeoutSignal","milliseconds","abortController","message","name","anySignal","signals","signal","defaultFetchFn","args","defaultValidateStatus","response","defaultIsJsonContentType","headers","stripUndefined","obj","isPlainObject","copy","k","v","isJsonifiable","body","fetchBaseQuery","baseUrl","prepareHeaders","x","fetchFn","paramsSerializer","isJsonContentType","jsonContentType","jsonReplacer","defaultTimeout","globalResponseHandler","globalValidateStatus","baseFetchOptions","arg","api","extraOptions","getState","extra","endpoint","forced","type","meta","url","params","responseHandler","validateStatus","timeout","rest","config","anySignal","timeoutSignal","bodyIsJsonifiable","divider","query","joinUrls","request","e","responseClone","resultData","responseText","handleResponseError","handleResponse","r","text","HandledError","value","meta","defaultBackoff","attempt","maxRetries","signal","attempts","timeout","resolve","reject","timeoutId","abortHandler","fail","error","meta","HandledError","failIfAborted","EMPTY_OPTIONS","retryWithBackoff","baseQuery","defaultOptions","args","api","extraOptions","possibleMaxRetries","options","_","__","retry","result","e","backoffError","INTERNAL_PREFIX","ONLINE","OFFLINE","FOCUS","FOCUSED","VISIBILITYCHANGE","onFocus","createAction","onFocusLost","onOnline","onOffline","actions","initialized","setupListeners","dispatch","customHandler","defaultHandler","handleFocus","handleFocusLost","handleOnline","handleOffline","action","handleVisibilityChange","unsubscribe","updateListeners","add","handlers","event","handler","ENDPOINT_QUERY","ENDPOINT_MUTATION","ENDPOINT_INFINITEQUERY","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","isAnyQueryDefinition","calculateProvidedBy","description","result","error","queryArg","meta","assertTagTypes","finalDescription","isFunction","filterMap","isNotNullish","tag","expandTagDescription","t","current","isDraft","applyPatches","original","isDraftable","produceWithPatches","enablePatches","asSafePromise","promise","fallback","getEndpointDefinition","context","endpointName","forceQueryFnSymbol","isUpsertQuery","arg","buildInitiate","serializeQueryArgs","queryThunk","infiniteQueryThunk","mutationThunk","api","context","getInternalState","getRunningQueries","dispatch","getRunningMutations","unsubscribeQueryResult","removeMutationResult","updateSubscriptionOptions","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningQueryThunk","getRunningMutationThunk","getRunningQueriesThunk","getRunningMutationsThunk","endpointName","queryArgs","endpointDefinition","getEndpointDefinition","queryCacheKey","_endpointName","fixedCacheKeyOrRequestId","filterNullishValues","middlewareWarning","buildInitiateAnyQuery","queryAction","subscribe","forceRefetch","subscriptionOptions","forceQueryFn","rest","getState","thunk","commonThunkArgs","ENDPOINT_QUERY","isQueryDefinition","direction","initialPageParam","refetchCachedPages","selector","thunkResult","stateAfter","requestId","abort","skippedSynchronously","runningQuery","selectFromState","statePromise","result","options","runningQueries","track","fixedCacheKey","unwrap","returnValuePromise","asSafePromise","data","error","reset","ret","runningMutations","SchemaError","NamedSchemaError","issues","value","schemaName","_bqMeta","shouldSkip","skipSchemaValidation","parseWithSchema","schema","data","bqMeta","result","defaultTransformResponse","baseQueryReturnValue","addShouldAutoBatch","arg","SHOULD_AUTOBATCH","buildThunks","reducerPath","baseQuery","endpointDefinitions","serializeQueryArgs","api","assertTagType","selectors","onSchemaFailure","globalCatchSchemaFailure","globalSkipSchemaValidation","patchQueryData","endpointName","patches","updateProvided","dispatch","getState","endpointDefinition","queryCacheKey","newValue","providedTags","calculateProvidedBy","addToStart","items","item","max","newItems","addToEnd","updateQueryData","updateRecipe","currentState","ret","STATUS_UNINITIALIZED","isDraftable","value","inversePatches","produceWithPatches","upsertQueryData","forceQueryFnSymbol","getTransformCallbackForEndpoint","transformFieldName","executeEndpoint","signal","abort","rejectWithValue","fulfillWithValue","extra","metaSchema","skipSchemaValidation","isQuery","ENDPOINT_QUERY","transformResponse","baseQueryApi","isForcedQuery","forceQueryFn","finalQueryReturnValue","fetchPage","data","param","maxPages","previous","finalQueryArg","pageResponse","executeRequest","addTo","result","extraOptions","argSchema","rawResponseSchema","responseSchema","shouldSkip","parseWithSchema","HandledError","transformedResponse","infiniteQueryOptions","refetchCachedPages","blankData","cachedData","existingData","getPreviousPageParam","getNextPageParam","initialPageParam","cachedPageParams","firstPageParam","totalPages","i","error","caughtError","transformErrorResponse","rawErrorResponseSchema","errorResponseSchema","meta","transformedErrorResponse","e","NamedSchemaError","info","catchSchemaFailure","state","requestState","baseFetchOnMountOrArgChange","fulfilledVal","refetchVal","createQueryThunk","createAsyncThunk","isInfiniteQueryDefinition","queryThunkArg","currentArg","previousArg","direction","isUpsertQuery","isQueryDefinition","queryThunk","infiniteQueryThunk","mutationThunk","hasTheForce","options","hasMaxAge","prefetch","force","maxAge","queryAction","latestStateValue","lastFulfilledTs","matchesEndpoint","action","buildMatchThunkActions","thunk","isAllOf","isPending","isFulfilled","isRejected","pages","pageParams","queryArg","lastIndex","calculateProvidedByThunk","type","isRejectedWithValue","getCurrent","value","isDraft","current","updateQuerySubstateIfExists","state","queryCacheKey","update","substate","getMutationCacheKey","id","updateMutationSubstateIfExists","initialState","buildSlice","reducerPath","queryThunk","mutationThunk","serializeQueryArgs","definitions","apiUid","extractRehydrationInfo","hasRehydrationInfo","assertTagType","config","resetApiState","createAction","writePendingCacheEntry","draft","arg","upserting","meta","STATUS_UNINITIALIZED","STATUS_PENDING","endpointDefinition","isInfiniteQueryDefinition","writeFulfilledCacheEntry","payload","merge","STATUS_FULFILLED","fulfilledTimeStamp","baseQueryMeta","requestId","newData","createNextState","draftSubstateData","copyWithStructuralSharing","isDraft","original","querySlice","createSlice","prepareAutoBatched","action","entry","value","endpointName","ENDPOINT_QUERY","SHOULD_AUTOBATCH","nanoid","patches","applyPatches","builder","isUpsertQuery","condition","error","STATUS_REJECTED","queries","key","mutationSlice","cacheKey","startedTimeStamp","mutations","initialInvalidationState","invalidationSlice","providedTags","removeCacheKeyFromTags","type","subscribedQueries","provided","incomingTags","cacheKeys","isAnyOf","isFulfilled","isRejectedWithValue","writeProvidedTagsForQueries","mockActions","queryDescription","existingTags","getCurrent","tag","tagType","tagId","tagSubscriptions","qc","actions","providedByEntries","calculateProvidedByThunk","subscriptionSlice","d","internalSubscriptionsSlice","configSlice","isOnline","isDocumentVisible","onOnline","onOffline","onFocus","onFocusLost","combinedReducer","combineReducers","reducer","skipToken","initialSubState","STATUS_UNINITIALIZED","defaultQuerySubState","createNextState","defaultMutationSubState","buildSelectors","serializeQueryArgs","reducerPath","createSelector","selectSkippedQuery","state","selectSkippedMutation","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","selectInvalidatedBy","selectCachedArgsForQuery","selectApiState","selectQueries","selectMutations","selectQueryEntry","selectConfig","withRequestFlags","substate","getRequestStatusFlags","rootState","cacheKey","buildAnyQuerySelector","endpointName","endpointDefinition","combiner","queryArgs","serializedArgs","infiniteQueryOptions","withInfiniteQueryResultFlags","stateWithRequestFlags","isLoading","isError","direction","isForward","isBackward","getHasNextPage","getHasPreviousPage","id","mutationId","getMutationCacheKey","tags","apiState","toInvalidate","finalTags","filterMap","isNotNullish","expandTagDescription","tag","provided","invalidateSubscriptions","invalidate","queryCacheKey","querySubState","queryName","entry","options","data","queryArg","getNextPageParam","getPreviousPageParam","_formatProdErrorMessage","cache","defaultSerializeQueryArgs","endpointName","queryArgs","serialized","cached","stringified","key","value","isPlainObject","acc","weakMapMemoize","buildCreateApi","modules","options","extractRehydrationInfo","action","optionsWithDefaults","queryArgsApi","finalSerializeQueryArgs","defaultSerializeQueryArgs","endpointSQA","initialResult","context","fn","nanoid","api","injectEndpoints","addTagTypes","endpoints","eT","endpointName","partialDefinition","getEndpointDefinition","initializedModules","m","inject","evaluatedEndpoints","x","ENDPOINT_QUERY","ENDPOINT_MUTATION","ENDPOINT_INFINITEQUERY","definition","_formatProdErrorMessage","_formatProdErrorMessage","_NEVER","fakeBaseQuery","safeAssign","target","args","buildBatchedActionsHandler","api","queryThunk","internalState","mwApi","subscriptionsPrefix","previousSubscriptions","updateSyncTimer","updateSubscriptionOptions","unsubscribeQueryResult","actuallyMutateSubscriptions","currentSubscriptions","action","queryCacheKey","requestId","options","sub","arg","substate","getOrInsertComputed","createNewMap","mutated","condition","getSubscriptions","subscriptionSelectors","serializeSubscriptions","k","v","didMutate","actionShouldContinue","newSubscriptions","patches","produceWithPatches","isSubscriptionSliceAction","isAdditionalSubscriptionAction","THIRTY_TWO_BIT_MAX_TIMER_SECONDS","buildCacheCollectionHandler","reducerPath","api","queryThunk","context","internalState","selectQueryEntry","selectConfig","getRunningQueryThunk","mwApi","removeQueryResult","unsubscribeQueryResult","cacheEntriesUpserted","canTriggerUnsubscribe","isAnyOf","anySubscriptionsRemainingForKey","queryCacheKey","subscriptions","currentRemovalTimeouts","abortAllPromises","promiseMap","promise","handler","action","state","config","queryCacheKeys","entry","handleUnsubscribeMany","key","timeout","queries","cacheKeys","handleUnsubscribe","endpointName","keepUnusedDataFor","getEndpointDefinition","finalKeepUnusedDataFor","currentTimeout","neverResolvedError","buildCacheLifecycleHandler","api","reducerPath","context","queryThunk","mutationThunk","internalState","selectQueryEntry","selectApiState","isQueryThunk","isAsyncThunkAction","isMutationThunk","isFulfilledThunk","isFulfilled","lifecycleMap","removeQueryResult","removeMutationResult","cacheEntriesUpserted","resolveLifecycleEntry","cacheKey","data","meta","lifecycle","removeLifecycleEntry","getActionMetaFields","action","arg","requestId","endpointName","originalArgs","handler","mwApi","stateBefore","getCacheKey","checkForNewCacheKey","oldEntry","newEntry","handleNewKey","queryDescription","value","queryCacheKey","getMutationCacheKey","endpointDefinition","getEndpointDefinition","onCacheEntryAdded","cacheEntryRemoved","resolve","cacheDataLoaded","selector","isAnyQueryDefinition","extra","_","__","lifecycleApi","updateRecipe","runningHandler","e","buildDevCheckHandler","api","apiUid","reducerPath","action","mwApi","buildInvalidationByTagsHandler","reducerPath","context","endpointDefinitions","mutationThunk","queryThunk","api","assertTagType","refetchQuery","internalState","removeQueryResult","isThunkActionWithTags","isAnyOf","isFulfilled","isRejectedWithValue","isQueryEnd","isRejected","pendingTagInvalidations","pendingRequestCount","handler","action","mwApi","invalidateTags","calculateProvidedByThunk","calculateProvidedBy","hasPendingRequests","newTags","rootState","state","tags","toInvalidate","valuesArray","queryCacheKey","querySubState","subscriptionSubState","getOrInsertComputed","createNewMap","STATUS_UNINITIALIZED","buildPollingHandler","reducerPath","queryThunk","api","refetchQuery","internalState","currentPolls","currentSubscriptions","pendingPollingUpdates","pollingUpdateTimer","handler","action","mwApi","schedulePollingUpdate","startNextPoll","clearPolls","queryCacheKey","key","updatePollingInterval","state","querySubState","subscriptions","STATUS_UNINITIALIZED","lowestPollingInterval","skipPollingIfUnfocused","findLowestPollingInterval","currentPoll","nextPollTimestamp","cleanupPollForKey","existingPoll","subscribers","entry","buildQueryLifecycleHandler","api","context","queryThunk","mutationThunk","isPendingThunk","isPending","isRejectedThunk","isRejected","isFullfilledThunk","isFulfilled","lifecycleMap","action","mwApi","requestId","endpointName","originalArgs","endpointDefinition","getEndpointDefinition","onQueryStarted","lifecycle","queryFulfilled","resolve","reject","selector","isAnyQueryDefinition","extra","_","__","lifecycleApi","updateRecipe","baseQueryMeta","rejectedWithValue","buildWindowEventHandler","reducerPath","context","api","refetchQuery","internalState","removeQueryResult","handler","action","mwApi","onFocus","refetchValidQueries","onOnline","type","state","queries","subscriptions","queryCacheKey","querySubState","subscriptionSubState","values","sub","STATUS_UNINITIALIZED","buildMiddleware","input","reducerPath","queryThunk","api","context","getInternalState","apiUid","actions","createAction","isThisApiSliceAction","action","handlerBuilders","buildDevCheckHandler","buildCacheCollectionHandler","buildInvalidationByTagsHandler","buildPollingHandler","buildCacheLifecycleHandler","buildQueryLifecycleHandler","mwApi","initialized","internalState","builderArgs","refetchQuery","handlers","build","batchedActionsHandler","buildBatchedActionsHandler","windowEventsHandler","buildWindowEventHandler","next","isAction","mwApiWithNext","stateBefore","actionShouldContinue","internalProbeResult","res","handler","querySubState","coreModuleName","coreModule","createSelector","api","baseQuery","tagTypes","reducerPath","serializeQueryArgs","keepUnusedDataFor","refetchOnMountOrArgChange","refetchOnFocus","refetchOnReconnect","invalidationBehavior","onSchemaFailure","catchSchemaFailure","skipSchemaValidation","context","enablePatches","assertTagType","tag","onOnline","onOffline","onFocus","onFocusLost","selectors","buildSelectors","selectInvalidatedBy","selectCachedArgsForQuery","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","safeAssign","queryThunk","infiniteQueryThunk","mutationThunk","patchQueryData","updateQueryData","upsertQueryData","prefetch","buildMatchThunkActions","buildThunks","reducer","sliceActions","buildSlice","internalStateMap","getInternalState","dispatch","getOrInsertComputed","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningMutationThunk","getRunningMutationsThunk","getRunningQueriesThunk","getRunningQueryThunk","buildInitiate","middleware","middlewareActions","buildMiddleware","endpointName","definition","anyApi","endpoint","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","createApi","buildCreateApi","coreModule"]}
Index: node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3116 @@
+var __defProp = Object.defineProperty;
+var __defProps = Object.defineProperties;
+var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
+var __getOwnPropSymbols = Object.getOwnPropertySymbols;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __propIsEnum = Object.prototype.propertyIsEnumerable;
+var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __spreadValues = (a, b) => {
+  for (var prop in b || (b = {}))
+    if (__hasOwnProp.call(b, prop))
+      __defNormalProp(a, prop, b[prop]);
+  if (__getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(b)) {
+      if (__propIsEnum.call(b, prop))
+        __defNormalProp(a, prop, b[prop]);
+    }
+  return a;
+};
+var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
+var __restKey = (key) => typeof key === "symbol" ? key : key + "";
+var __objRest = (source, exclude) => {
+  var target = {};
+  for (var prop in source)
+    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
+      target[prop] = source[prop];
+  if (source != null && __getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(source)) {
+      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
+        target[prop] = source[prop];
+    }
+  return target;
+};
+
+// src/query/core/apiState.ts
+var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
+  QueryStatus7["uninitialized"] = "uninitialized";
+  QueryStatus7["pending"] = "pending";
+  QueryStatus7["fulfilled"] = "fulfilled";
+  QueryStatus7["rejected"] = "rejected";
+  return QueryStatus7;
+})(QueryStatus || {});
+var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
+var STATUS_PENDING = "pending" /* pending */;
+var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
+var STATUS_REJECTED = "rejected" /* rejected */;
+function getRequestStatusFlags(status) {
+  return {
+    status,
+    isUninitialized: status === STATUS_UNINITIALIZED,
+    isLoading: status === STATUS_PENDING,
+    isSuccess: status === STATUS_FULFILLED,
+    isError: status === STATUS_REJECTED
+  };
+}
+
+// src/query/core/rtkImports.ts
+import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
+
+// src/query/utils/copyWithStructuralSharing.ts
+var isPlainObject2 = isPlainObject;
+function copyWithStructuralSharing(oldObj, newObj) {
+  if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
+    return newObj;
+  }
+  const newKeys = Object.keys(newObj);
+  const oldKeys = Object.keys(oldObj);
+  let isSameObject = newKeys.length === oldKeys.length;
+  const mergeObj = Array.isArray(newObj) ? [] : {};
+  for (const key of newKeys) {
+    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
+    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
+  }
+  return isSameObject ? oldObj : mergeObj;
+}
+
+// src/query/utils/filterMap.ts
+function filterMap(array, predicate, mapper) {
+  return array.reduce((acc, item, i) => {
+    if (predicate(item, i)) {
+      acc.push(mapper(item, i));
+    }
+    return acc;
+  }, []).flat();
+}
+
+// src/query/utils/isAbsoluteUrl.ts
+function isAbsoluteUrl(url) {
+  return new RegExp(`(^|:)//`).test(url);
+}
+
+// src/query/utils/isDocumentVisible.ts
+function isDocumentVisible() {
+  if (typeof document === "undefined") {
+    return true;
+  }
+  return document.visibilityState !== "hidden";
+}
+
+// src/query/utils/isNotNullish.ts
+function isNotNullish(v) {
+  return v != null;
+}
+function filterNullishValues(map) {
+  var _a;
+  return [...(_a = map == null ? void 0 : map.values()) != null ? _a : []].filter(isNotNullish);
+}
+
+// src/query/utils/isOnline.ts
+function isOnline() {
+  return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
+}
+
+// src/query/utils/joinUrls.ts
+var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
+var withoutLeadingSlash = (url) => url.replace(/^\//, "");
+function joinUrls(base, url) {
+  if (!base) {
+    return url;
+  }
+  if (!url) {
+    return base;
+  }
+  if (isAbsoluteUrl(url)) {
+    return url;
+  }
+  const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
+  base = withoutTrailingSlash(base);
+  url = withoutLeadingSlash(url);
+  return `${base}${delimiter}${url}`;
+}
+
+// src/query/utils/getOrInsert.ts
+function getOrInsertComputed(map, key, compute) {
+  if (map.has(key)) return map.get(key);
+  return map.set(key, compute(key)).get(key);
+}
+var createNewMap = () => /* @__PURE__ */ new Map();
+
+// src/query/utils/signals.ts
+var timeoutSignal = (milliseconds) => {
+  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;
+};
+var anySignal = (...signals) => {
+  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
+  const abortController = new AbortController();
+  for (const signal of signals) {
+    signal.addEventListener("abort", () => abortController.abort(signal.reason), {
+      signal: abortController.signal,
+      once: true
+    });
+  }
+  return abortController.signal;
+};
+
+// src/query/fetchBaseQuery.ts
+var defaultFetchFn = (...args) => fetch(...args);
+var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
+var defaultIsJsonContentType = (headers) => (
+  /*applicat*/
+  /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
+);
+function stripUndefined(obj) {
+  if (!isPlainObject(obj)) {
+    return obj;
+  }
+  const copy = __spreadValues({}, obj);
+  for (const [k, v] of Object.entries(copy)) {
+    if (v === void 0) delete copy[k];
+  }
+  return copy;
+}
+var isJsonifiable = (body) => typeof body === "object" && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === "function");
+function fetchBaseQuery(_a = {}) {
+  var _b = _a, {
+    baseUrl,
+    prepareHeaders = (x) => x,
+    fetchFn = defaultFetchFn,
+    paramsSerializer,
+    isJsonContentType = defaultIsJsonContentType,
+    jsonContentType = "application/json",
+    jsonReplacer,
+    timeout: defaultTimeout,
+    responseHandler: globalResponseHandler,
+    validateStatus: globalValidateStatus
+  } = _b, baseFetchOptions = __objRest(_b, [
+    "baseUrl",
+    "prepareHeaders",
+    "fetchFn",
+    "paramsSerializer",
+    "isJsonContentType",
+    "jsonContentType",
+    "jsonReplacer",
+    "timeout",
+    "responseHandler",
+    "validateStatus"
+  ]);
+  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;
+    let _a2 = typeof arg == "string" ? {
+      url: arg
+    } : arg, {
+      url,
+      headers = new Headers(baseFetchOptions.headers),
+      params = void 0,
+      responseHandler = globalResponseHandler != null ? globalResponseHandler : "json",
+      validateStatus = globalValidateStatus != null ? globalValidateStatus : defaultValidateStatus,
+      timeout = defaultTimeout
+    } = _a2, rest = __objRest(_a2, [
+      "url",
+      "headers",
+      "params",
+      "responseHandler",
+      "validateStatus",
+      "timeout"
+    ]);
+    let config = __spreadValues(__spreadProps(__spreadValues({}, 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);
+    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);
+    }
+    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, */*");
+      }
+    }
+    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;
+    let responseText = "";
+    try {
+      let handleResponseError;
+      await Promise.all([
+        handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
+        // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
+        // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
+        responseClone.text().then((r) => responseText = r, () => {
+        })
+      ]);
+      if (handleResponseError) throw handleResponseError;
+    } catch (e) {
+      return {
+        error: {
+          status: "PARSING_ERROR",
+          originalStatus: response.status,
+          data: responseText,
+          error: String(e)
+        },
+        meta
+      };
+    }
+    return validateStatus(response, resultData) ? {
+      data: resultData,
+      meta
+    } : {
+      error: {
+        status: response.status,
+        data: resultData
+      },
+      meta
+    };
+  };
+  async function handleResponse(response, responseHandler) {
+    if (typeof responseHandler === "function") {
+      return responseHandler(response);
+    }
+    if (responseHandler === "content-type") {
+      responseHandler = isJsonContentType(response.headers) ? "json" : "text";
+    }
+    if (responseHandler === "json") {
+      const text = await response.text();
+      return text.length ? JSON.parse(text) : null;
+    }
+    return response.text();
+  }
+}
+
+// src/query/HandledError.ts
+var HandledError = class {
+  constructor(value, meta = void 0) {
+    this.value = value;
+    this.meta = meta;
+  }
+};
+
+// src/query/retry.ts
+async function defaultBackoff(attempt = 0, maxRetries = 5, signal) {
+  const attempts = Math.min(attempt, maxRetries);
+  const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
+  await new Promise((resolve, reject) => {
+    const timeoutId = setTimeout(() => resolve(), timeout);
+    if (signal) {
+      const abortHandler = () => {
+        clearTimeout(timeoutId);
+        reject(new Error("Aborted"));
+      };
+      if (signal.aborted) {
+        clearTimeout(timeoutId);
+        reject(new Error("Aborted"));
+      } else {
+        signal.addEventListener("abort", abortHandler, {
+          once: true
+        });
+      }
+    }
+  });
+}
+function fail(error, meta) {
+  throw Object.assign(new HandledError({
+    error,
+    meta
+  }), {
+    throwImmediately: true
+  });
+}
+function failIfAborted(signal) {
+  if (signal.aborted) {
+    fail({
+      status: "CUSTOM_ERROR",
+      error: "Aborted"
+    });
+  }
+}
+var EMPTY_OPTIONS = {};
+var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
+  const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
+  const [maxRetries] = possibleMaxRetries.slice(-1);
+  const defaultRetryCondition = (_, __, {
+    attempt
+  }) => attempt <= maxRetries;
+  const options = __spreadValues(__spreadValues({
+    maxRetries,
+    backoff: defaultBackoff,
+    retryCondition: defaultRetryCondition
+  }, defaultOptions), extraOptions);
+  let retry2 = 0;
+  while (true) {
+    failIfAborted(api.signal);
+    try {
+      const result = await baseQuery(args, api, extraOptions);
+      if (result.error) {
+        throw new HandledError(result);
+      }
+      return result;
+    } catch (e) {
+      retry2++;
+      if (e.throwImmediately) {
+        if (e instanceof HandledError) {
+          return e.value;
+        }
+        throw e;
+      }
+      if (e instanceof HandledError) {
+        if (!options.retryCondition(e.value.error, args, {
+          attempt: retry2,
+          baseQueryApi: api,
+          extraOptions
+        })) {
+          return e.value;
+        }
+      } else {
+        if (retry2 > options.maxRetries) {
+          return {
+            error: e
+          };
+        }
+      }
+      failIfAborted(api.signal);
+      try {
+        await options.backoff(retry2, options.maxRetries, api.signal);
+      } catch (backoffError) {
+        failIfAborted(api.signal);
+        throw backoffError;
+      }
+    }
+  }
+};
+var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
+  fail
+});
+
+// src/query/core/setupListeners.ts
+var INTERNAL_PREFIX = "__rtkq/";
+var ONLINE = "online";
+var OFFLINE = "offline";
+var FOCUS = "focus";
+var FOCUSED = "focused";
+var VISIBILITYCHANGE = "visibilitychange";
+var onFocus = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${FOCUSED}`);
+var onFocusLost = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);
+var onOnline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${ONLINE}`);
+var onOffline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${OFFLINE}`);
+var actions = {
+  onFocus,
+  onFocusLost,
+  onOnline,
+  onOffline
+};
+var initialized = false;
+function setupListeners(dispatch, customHandler) {
+  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) {
+        let updateListeners2 = function(add) {
+          Object.entries(handlers).forEach(([event, handler]) => {
+            if (add) {
+              window.addEventListener(event, handler, false);
+            } else {
+              window.removeEventListener(event, handler);
+            }
+          });
+        };
+        var updateListeners = updateListeners2;
+        const handlers = {
+          [FOCUS]: handleFocus,
+          [VISIBILITYCHANGE]: handleVisibilityChange,
+          [ONLINE]: handleOnline,
+          [OFFLINE]: handleOffline
+        };
+        updateListeners2(true);
+        initialized = true;
+        unsubscribe = () => {
+          updateListeners2(false);
+          initialized = false;
+        };
+      }
+    }
+    return unsubscribe;
+  }
+  return customHandler ? customHandler(dispatch, actions) : defaultHandler();
+}
+
+// src/query/endpointDefinitions.ts
+var ENDPOINT_QUERY = "query" /* query */;
+var ENDPOINT_MUTATION = "mutation" /* mutation */;
+var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
+function isQueryDefinition(e) {
+  return e.type === ENDPOINT_QUERY;
+}
+function isMutationDefinition(e) {
+  return e.type === ENDPOINT_MUTATION;
+}
+function isInfiniteQueryDefinition(e) {
+  return e.type === ENDPOINT_INFINITEQUERY;
+}
+function isAnyQueryDefinition(e) {
+  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);
+}
+function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
+  const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
+  if (finalDescription) {
+    return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
+  }
+  return [];
+}
+function isFunction(t) {
+  return typeof t === "function";
+}
+function expandTagDescription(description) {
+  return typeof description === "string" ? {
+    type: description
+  } : description;
+}
+
+// src/query/utils/immerImports.ts
+import { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from "immer";
+
+// src/query/core/buildInitiate.ts
+import { formatProdErrorMessage as _formatProdErrorMessage } from "@reduxjs/toolkit";
+
+// src/tsHelpers.ts
+function asSafePromise(promise, fallback) {
+  return promise.catch(fallback);
+}
+
+// src/query/apiTypes.ts
+var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
+
+// src/query/core/buildInitiate.ts
+var forceQueryFnSymbol = Symbol("forceQueryFn");
+var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
+function buildInitiate({
+  serializeQueryArgs,
+  queryThunk,
+  infiniteQueryThunk,
+  mutationThunk,
+  api,
+  context,
+  getInternalState
+}) {
+  const getRunningQueries = (dispatch) => {
+    var _a;
+    return (_a = getInternalState(dispatch)) == null ? void 0 : _a.runningQueries;
+  };
+  const getRunningMutations = (dispatch) => {
+    var _a;
+    return (_a = getInternalState(dispatch)) == null ? void 0 : _a.runningMutations;
+  };
+  const {
+    unsubscribeQueryResult,
+    removeMutationResult,
+    updateSubscriptionOptions
+  } = api.internalActions;
+  return {
+    buildInitiateQuery,
+    buildInitiateInfiniteQuery,
+    buildInitiateMutation,
+    getRunningQueryThunk,
+    getRunningMutationThunk,
+    getRunningQueriesThunk,
+    getRunningMutationsThunk
+  };
+  function getRunningQueryThunk(endpointName, queryArgs) {
+    return (dispatch) => {
+      var _a;
+      const endpointDefinition = getEndpointDefinition(context, endpointName);
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      });
+      return (_a = getRunningQueries(dispatch)) == null ? void 0 : _a.get(queryCacheKey);
+    };
+  }
+  function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
+    return (dispatch) => {
+      var _a;
+      return (_a = getRunningMutations(dispatch)) == null ? void 0 : _a.get(fixedCacheKeyOrRequestId);
+    };
+  }
+  function getRunningQueriesThunk() {
+    return (dispatch) => filterNullishValues(getRunningQueries(dispatch));
+  }
+  function getRunningMutationsThunk() {
+    return (dispatch) => filterNullishValues(getRunningMutations(dispatch));
+  }
+  function middlewareWarning(dispatch) {
+    if (process.env.NODE_ENV !== "production") {
+      if (middlewareWarning.triggered) return;
+      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
+      middlewareWarning.triggered = true;
+      if (typeof returnedValue !== "object" || typeof (returnedValue == null ? void 0 : returnedValue.type) === "string") {
+        throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+You must add the middleware for RTK-Query to function correctly!`);
+      }
+    }
+  }
+  function buildInitiateAnyQuery(endpointName, endpointDefinition) {
+    const queryAction = (arg, _a = {}) => {
+      var _b = _a, {
+        subscribe = true,
+        forceRefetch,
+        subscriptionOptions,
+        [forceQueryFnSymbol]: forceQueryFn
+      } = _b, rest = __objRest(_b, [
+        "subscribe",
+        "forceRefetch",
+        "subscriptionOptions",
+        __restKey(forceQueryFnSymbol)
+      ]);
+      return (dispatch, getState) => {
+        var _a2;
+        const queryCacheKey = serializeQueryArgs({
+          queryArgs: arg,
+          endpointDefinition,
+          endpointName
+        });
+        let thunk;
+        const commonThunkArgs = __spreadProps(__spreadValues({}, rest), {
+          type: ENDPOINT_QUERY,
+          subscribe,
+          forceRefetch,
+          subscriptionOptions,
+          endpointName,
+          originalArgs: arg,
+          queryCacheKey,
+          [forceQueryFnSymbol]: forceQueryFn
+        });
+        if (isQueryDefinition(endpointDefinition)) {
+          thunk = queryThunk(commonThunkArgs);
+        } else {
+          const {
+            direction,
+            initialPageParam,
+            refetchCachedPages
+          } = rest;
+          thunk = infiniteQueryThunk(__spreadProps(__spreadValues({}, commonThunkArgs), {
+            // Supply these even if undefined. This helps with a field existence
+            // check over in `buildSlice.ts`
+            direction,
+            initialPageParam,
+            refetchCachedPages
+          }));
+        }
+        const selector = api.endpoints[endpointName].select(arg);
+        const thunkResult = dispatch(thunk);
+        const stateAfter = selector(getState());
+        middlewareWarning(dispatch);
+        const {
+          requestId,
+          abort
+        } = thunkResult;
+        const skippedSynchronously = stateAfter.requestId !== requestId;
+        const runningQuery = (_a2 = getRunningQueries(dispatch)) == null ? void 0 : _a2.get(queryCacheKey);
+        const selectFromState = () => selector(getState());
+        const statePromise = Object.assign(forceQueryFn ? (
+          // a query has been forced (upsertQueryData)
+          // -> we want to resolve it once data has been written with the data that will be written
+          thunkResult.then(selectFromState)
+        ) : skippedSynchronously && !runningQuery ? (
+          // a query has been skipped due to a condition and we do not have any currently running query
+          // -> we want to resolve it immediately with the current data
+          Promise.resolve(stateAfter)
+        ) : (
+          // query just started or one is already in flight
+          // -> wait for the running query, then resolve with data from after that
+          Promise.all([runningQuery, thunkResult]).then(selectFromState)
+        ), {
+          arg,
+          requestId,
+          subscriptionOptions,
+          queryCacheKey,
+          abort,
+          async unwrap() {
+            const result = await statePromise;
+            if (result.isError) {
+              throw result.error;
+            }
+            return result.data;
+          },
+          refetch: (options) => dispatch(queryAction(arg, __spreadValues({
+            subscribe: false,
+            forceRefetch: true
+          }, options))),
+          unsubscribe() {
+            if (subscribe) dispatch(unsubscribeQueryResult({
+              queryCacheKey,
+              requestId
+            }));
+          },
+          updateSubscriptionOptions(options) {
+            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, endpointDefinition) {
+    const queryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
+    return queryAction;
+  }
+  function buildInitiateInfiniteQuery(endpointName, endpointDefinition) {
+    const infiniteQueryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
+    return infiniteQueryAction;
+  }
+  function buildInitiateMutation(endpointName) {
+    return (arg, {
+      track = true,
+      fixedCacheKey
+    } = {}) => (dispatch, getState) => {
+      const thunk = mutationThunk({
+        type: "mutation",
+        endpointName,
+        originalArgs: arg,
+        track,
+        fixedCacheKey
+      });
+      const thunkResult = dispatch(thunk);
+      middlewareWarning(dispatch);
+      const {
+        requestId,
+        abort,
+        unwrap
+      } = thunkResult;
+      const returnValuePromise = 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;
+    };
+  }
+}
+
+// src/query/standardSchema.ts
+import { SchemaError } from "@standard-schema/utils";
+var NamedSchemaError = class extends SchemaError {
+  constructor(issues, value, schemaName, _bqMeta) {
+    super(issues);
+    this.value = value;
+    this.schemaName = schemaName;
+    this._bqMeta = _bqMeta;
+  }
+};
+var shouldSkip = (skipSchemaValidation, schemaName) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;
+async function parseWithSchema(schema, data, schemaName, bqMeta) {
+  const result = await schema["~standard"].validate(data);
+  if (result.issues) {
+    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);
+  }
+  return result.value;
+}
+
+// src/query/core/buildThunks.ts
+function defaultTransformResponse(baseQueryReturnValue) {
+  return baseQueryReturnValue;
+}
+var addShouldAutoBatch = (arg = {}) => {
+  return __spreadProps(__spreadValues({}, arg), {
+    [SHOULD_AUTOBATCH]: true
+  });
+};
+function buildThunks({
+  reducerPath,
+  baseQuery,
+  context: {
+    endpointDefinitions
+  },
+  serializeQueryArgs,
+  api,
+  assertTagType,
+  selectors,
+  onSchemaFailure,
+  catchSchemaFailure: globalCatchSchemaFailure,
+  skipSchemaValidation: globalSkipSchemaValidation
+}) {
+  const patchQueryData = (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()
+    );
+    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
+    dispatch(api.internalActions.updateProvidedBy([{
+      queryCacheKey,
+      providedTags
+    }]));
+  };
+  function addToStart(items, item, max = 0) {
+    const newItems = [item, ...items];
+    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
+  }
+  function addToEnd(items, item, max = 0) {
+    const newItems = [...items, item];
+    return max && newItems.length > max ? newItems.slice(1) : newItems;
+  }
+  const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
+    const endpointDefinition = api.endpoints[endpointName];
+    const currentState = endpointDefinition.select(arg)(
+      // Work around TS 4.1 mismatch
+      getState()
+    );
+    const ret = {
+      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 = (endpointName, arg, value) => (dispatch) => {
+    const res = dispatch(api.endpoints[endpointName].initiate(arg, {
+      subscribe: false,
+      forceRefetch: true,
+      [forceQueryFnSymbol]: () => ({
+        data: value
+      })
+    }));
+    return res;
+  };
+  const getTransformCallbackForEndpoint = (endpointDefinition, transformFieldName) => {
+    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName] : defaultTransformResponse;
+  };
+  const executeEndpoint = async (arg, {
+    signal,
+    abort,
+    rejectWithValue,
+    fulfillWithValue,
+    dispatch,
+    getState,
+    extra
+  }) => {
+    var _a, _b, _c, _d, _e, _f;
+    const endpointDefinition = endpointDefinitions[arg.endpointName];
+    const {
+      metaSchema,
+      skipSchemaValidation = globalSkipSchemaValidation
+    } = endpointDefinition;
+    const isQuery = arg.type === ENDPOINT_QUERY;
+    try {
+      let transformResponse = defaultTransformResponse;
+      const baseQueryApi = {
+        signal,
+        abort,
+        dispatch,
+        getState,
+        extra,
+        endpoint: arg.endpointName,
+        type: arg.type,
+        forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
+        queryCacheKey: isQuery ? arg.queryCacheKey : void 0
+      };
+      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
+      let finalQueryReturnValue;
+      const fetchPage = async (data, param, maxPages, previous) => {
+        if (param == null && data.pages.length) {
+          return Promise.resolve({
+            data
+          });
+        }
+        const finalQueryArg = {
+          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
+        };
+      };
+      async function executeRequest(finalQueryArg) {
+        let result;
+        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) {
+          result = forceQueryFn();
+        } else if (endpointDefinition.query) {
+          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformResponse");
+          result = await baseQuery(endpointDefinition.query(finalQueryArg), baseQueryApi, extraOptions);
+        } else {
+          result = await endpointDefinition.queryFn(finalQueryArg, baseQueryApi, extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, extraOptions));
+        }
+        if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+          const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
+          let err;
+          if (!result) {
+            err = `${what} did not return anything.`;
+          } else if (typeof result !== "object") {
+            err = `${what} did not return an object.`;
+          } else if (result.error && result.data) {
+            err = `${what} returned an object containing both \`error\` and \`result\`.`;
+          } else if (result.error === void 0 && result.data === void 0) {
+            err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
+          } else {
+            for (const key of Object.keys(result)) {
+              if (key !== "error" && key !== "data" && key !== "meta") {
+                err = `The object returned by ${what} has the unknown property ${key}.`;
+                break;
+              }
+            }
+          }
+          if (err) {
+            console.error(`Error encountered handling the endpoint ${arg.endpointName}.
+                  ${err}
+                  It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
+                  Object returned was:`, result);
+          }
+        }
+        if (result.error) throw new HandledError(result.error, result.meta);
+        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 __spreadProps(__spreadValues({}, result), {
+          data: transformedResponse
+        });
+      }
+      if (isQuery && "infiniteQueryOptions" in endpointDefinition) {
+        const {
+          infiniteQueryOptions
+        } = endpointDefinition;
+        const {
+          maxPages = Infinity
+        } = infiniteQueryOptions;
+        const refetchCachedPages = (_b = (_a = arg.refetchCachedPages) != null ? _a : infiniteQueryOptions.refetchCachedPages) != null ? _b : true;
+        let result;
+        const blankData = {
+          pages: [],
+          pageParams: []
+        };
+        const cachedData = (_c = selectors.selectQueryEntry(getState(), arg.queryCacheKey)) == null ? void 0 : _c.data;
+        const isForcedQueryNeedingRefetch = (
+          // arg.forceRefetch
+          isForcedQuery(arg, getState()) && !arg.direction
+        );
+        const existingData = isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData;
+        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 {
+          const {
+            initialPageParam = infiniteQueryOptions.initialPageParam
+          } = arg;
+          const cachedPageParams = (_d = cachedData == null ? void 0 : cachedData.pageParams) != null ? _d : [];
+          const firstPageParam = (_e = cachedPageParams[0]) != null ? _e : initialPageParam;
+          const totalPages = cachedPageParams.length;
+          result = await fetchPage(existingData, firstPageParam, maxPages);
+          if (forceQueryFn) {
+            result = {
+              data: result.data.pages[0]
+            };
+          }
+          if (refetchCachedPages) {
+            for (let i = 1; i < totalPages; i++) {
+              const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
+              result = await fetchPage(result.data, param, maxPages);
+            }
+          }
+        }
+        finalQueryReturnValue = result;
+      } else {
+        finalQueryReturnValue = await executeRequest(arg.originalArgs);
+      }
+      if (metaSchema && !shouldSkip(skipSchemaValidation, "meta") && finalQueryReturnValue.meta) {
+        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, "metaSchema", finalQueryReturnValue.meta);
+      }
+      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 = {
+            endpoint: arg.endpointName,
+            arg: arg.originalArgs,
+            type: arg.type,
+            queryCacheKey: isQuery ? arg.queryCacheKey : void 0
+          };
+          (_f = endpointDefinition.onSchemaFailure) == null ? void 0 : _f.call(endpointDefinition, caughtError, info);
+          onSchemaFailure == null ? void 0 : 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, state) {
+    var _a;
+    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);
+    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;
+    const fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
+    const refetchVal = (_a = arg.forceRefetch) != null ? _a : arg.subscribe && baseFetchOnMountOrArgChange;
+    if (refetchVal) {
+      return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
+    }
+    return false;
+  }
+  const createQueryThunk = () => {
+    const generatedQueryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
+      getPendingMeta({
+        arg
+      }) {
+        const endpointDefinition = endpointDefinitions[arg.endpointName];
+        return addShouldAutoBatch(__spreadValues({
+          startedTimeStamp: Date.now()
+        }, isInfiniteQueryDefinition(endpointDefinition) ? {
+          direction: arg.direction
+        } : {}));
+      },
+      condition(queryThunkArg, {
+        getState
+      }) {
+        var _a;
+        const state = getState();
+        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);
+        const fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
+        const currentArg = queryThunkArg.originalArgs;
+        const previousArg = requestState == null ? void 0 : requestState.originalArgs;
+        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];
+        const direction = queryThunkArg.direction;
+        if (isUpsertQuery(queryThunkArg)) {
+          return true;
+        }
+        if ((requestState == null ? void 0 : requestState.status) === "pending") {
+          return false;
+        }
+        if (isForcedQuery(queryThunkArg, state)) {
+          return true;
+        }
+        if (isQueryDefinition(endpointDefinition) && ((_a = endpointDefinition == null ? void 0 : endpointDefinition.forceRefetch) == null ? void 0 : _a.call(endpointDefinition, {
+          currentArg,
+          previousArg,
+          endpointState: requestState,
+          state
+        }))) {
+          return true;
+        }
+        if (fulfilledVal && !direction) {
+          return false;
+        }
+        return true;
+      },
+      dispatchConditionRejection: true
+    });
+    return generatedQueryThunk;
+  };
+  const queryThunk = createQueryThunk();
+  const infiniteQueryThunk = createQueryThunk();
+  const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
+    getPendingMeta() {
+      return addShouldAutoBatch({
+        startedTimeStamp: Date.now()
+      });
+    }
+  });
+  const hasTheForce = (options) => "force" in options;
+  const hasMaxAge = (options) => "ifOlderThan" in options;
+  const prefetch = (endpointName, arg, options = {}) => (dispatch, getState) => {
+    const force = hasTheForce(options) && options.force;
+    const maxAge = hasMaxAge(options) && options.ifOlderThan;
+    const queryAction = (force2 = true) => {
+      const options2 = {
+        forceRefetch: force2,
+        subscribe: false
+      };
+      return api.endpoints[endpointName].initiate(arg, options2);
+    };
+    const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
+    if (force) {
+      dispatch(queryAction());
+    } else if (maxAge) {
+      const lastFulfilledTs = latestStateValue == null ? void 0 : latestStateValue.fulfilledTimeStamp;
+      if (!lastFulfilledTs) {
+        dispatch(queryAction());
+        return;
+      }
+      const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
+      if (shouldRetrigger) {
+        dispatch(queryAction());
+      }
+    } else {
+      dispatch(queryAction(false));
+    }
+  };
+  function matchesEndpoint(endpointName) {
+    return (action) => {
+      var _a, _b;
+      return ((_b = (_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.arg) == null ? void 0 : _b.endpointName) === endpointName;
+    };
+  }
+  function buildMatchThunkActions(thunk, endpointName) {
+    return {
+      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
+      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
+      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
+    };
+  }
+  return {
+    queryThunk,
+    mutationThunk,
+    infiniteQueryThunk,
+    prefetch,
+    updateQueryData,
+    upsertQueryData,
+    patchQueryData,
+    buildMatchThunkActions
+  };
+}
+function getNextPageParam(options, {
+  pages,
+  pageParams
+}, queryArg) {
+  const lastIndex = pages.length - 1;
+  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);
+}
+function getPreviousPageParam(options, {
+  pages,
+  pageParams
+}, queryArg) {
+  var _a;
+  return (_a = options.getPreviousPageParam) == null ? void 0 : _a.call(options, pages[0], pages, pageParams[0], pageParams, queryArg);
+}
+function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
+  return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
+}
+
+// src/query/utils/getCurrent.ts
+function getCurrent(value) {
+  return isDraft(value) ? current(value) : value;
+}
+
+// src/query/core/buildSlice.ts
+function updateQuerySubstateIfExists(state, queryCacheKey, update) {
+  const substate = state[queryCacheKey];
+  if (substate) {
+    update(substate);
+  }
+}
+function getMutationCacheKey(id) {
+  var _a;
+  return (_a = "arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) != null ? _a : id.requestId;
+}
+function updateMutationSubstateIfExists(state, id, update) {
+  const substate = state[getMutationCacheKey(id)];
+  if (substate) {
+    update(substate);
+  }
+}
+var initialState = {};
+function buildSlice({
+  reducerPath,
+  queryThunk,
+  mutationThunk,
+  serializeQueryArgs,
+  context: {
+    endpointDefinitions: definitions,
+    apiUid,
+    extractRehydrationInfo,
+    hasRehydrationInfo
+  },
+  assertTagType,
+  config
+}) {
+  const resetApiState = createAction(`${reducerPath}/resetApiState`);
+  function writePendingCacheEntry(draft, arg, upserting, meta) {
+    var _a, _b;
+    (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {
+      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 !== void 0) {
+        substate.originalArgs = arg.originalArgs;
+      }
+      substate.startedTimeStamp = meta.startedTimeStamp;
+      const endpointDefinition = definitions[meta.arg.endpointName];
+      if (isInfiniteQueryDefinition(endpointDefinition) && "direction" in arg) {
+        ;
+        substate.direction = arg.direction;
+      }
+    });
+  }
+  function writeFulfilledCacheEntry(draft, meta, payload, upserting) {
+    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
+      var _a;
+      if (substate.requestId !== meta.requestId && !upserting) return;
+      const {
+        merge
+      } = definitions[meta.arg.endpointName];
+      substate.status = STATUS_FULFILLED;
+      if (merge) {
+        if (substate.data !== void 0) {
+          const {
+            fulfilledTimeStamp,
+            arg,
+            baseQueryMeta,
+            requestId
+          } = meta;
+          let newData = createNextState(substate.data, (draftSubstateData) => {
+            return merge(draftSubstateData, payload, {
+              arg: arg.originalArgs,
+              baseQueryMeta,
+              fulfilledTimeStamp,
+              requestId
+            });
+          });
+          substate.data = newData;
+        } else {
+          substate.data = payload;
+        }
+      } else {
+        substate.data = ((_a = definitions[meta.arg.endpointName].structuralSharing) != null ? _a : 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,
+    reducers: {
+      removeQueryResult: {
+        reducer(draft, {
+          payload: {
+            queryCacheKey
+          }
+        }) {
+          delete draft[queryCacheKey];
+        },
+        prepare: prepareAutoBatched()
+      },
+      cacheEntriesUpserted: {
+        reducer(draft, action) {
+          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) => {
+          const queryDescriptions = payload.map((entry) => {
+            const {
+              endpointName,
+              arg,
+              value
+            } = entry;
+            const endpointDefinition = definitions[endpointName];
+            const queryDescription = {
+              type: ENDPOINT_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
+          }
+        }) {
+          updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
+            substate.data = applyPatches(substate.data, patches.concat());
+          });
+        },
+        prepare: prepareAutoBatched()
+      }
+    },
+    extraReducers(builder) {
+      builder.addCase(queryThunk.pending, (draft, {
+        meta,
+        meta: {
+          arg
+        }
+      }) => {
+        const upserting = isUpsertQuery(arg);
+        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) {
+          } else {
+            if (substate.requestId !== requestId) return;
+            substate.status = STATUS_REJECTED;
+            substate.error = payload != null ? payload : error;
+          }
+        });
+      }).addMatcher(hasRehydrationInfo, (draft, action) => {
+        const {
+          queries
+        } = extractRehydrationInfo(action);
+        for (const [key, entry] of Object.entries(queries)) {
+          if (
+            // do not rehydrate entries that were currently in flight.
+            (entry == null ? void 0 : entry.status) === STATUS_FULFILLED || (entry == null ? void 0 : entry.status) === STATUS_REJECTED
+          ) {
+            draft[key] = entry;
+          }
+        }
+      });
+    }
+  });
+  const mutationSlice = createSlice({
+    name: `${reducerPath}/mutations`,
+    initialState,
+    reducers: {
+      removeMutationResult: {
+        reducer(draft, {
+          payload
+        }) {
+          const cacheKey = getMutationCacheKey(payload);
+          if (cacheKey in draft) {
+            delete draft[cacheKey];
+          }
+        },
+        prepare: prepareAutoBatched()
+      }
+    },
+    extraReducers(builder) {
+      builder.addCase(mutationThunk.pending, (draft, {
+        meta,
+        meta: {
+          requestId,
+          arg,
+          startedTimeStamp
+        }
+      }) => {
+        if (!arg.track) return;
+        draft[getMutationCacheKey(meta)] = {
+          requestId,
+          status: 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 != null ? payload : error;
+        });
+      }).addMatcher(hasRehydrationInfo, (draft, action) => {
+        const {
+          mutations
+        } = extractRehydrationInfo(action);
+        for (const [key, entry] of Object.entries(mutations)) {
+          if (
+            // do not rehydrate entries that were currently in flight.
+            ((entry == null ? void 0 : entry.status) === STATUS_FULFILLED || (entry == null ? void 0 : entry.status) === STATUS_REJECTED) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
+            key !== (entry == null ? void 0 : entry.requestId)
+          ) {
+            draft[key] = entry;
+          }
+        }
+      });
+    }
+  });
+  const initialInvalidationState = {
+    tags: {},
+    keys: {}
+  };
+  const invalidationSlice = createSlice({
+    name: `${reducerPath}/invalidation`,
+    initialState: initialInvalidationState,
+    reducers: {
+      updateProvidedBy: {
+        reducer(draft, action) {
+          var _a, _b, _c, _d, _e;
+          for (const {
+            queryCacheKey,
+            providedTags
+          } of action.payload) {
+            removeCacheKeyFromTags(draft, queryCacheKey);
+            for (const {
+              type,
+              id
+            } of providedTags) {
+              const subscribedQueries = (_e = (_c = (_b = (_a = draft.tags)[type]) != null ? _b : _a[type] = {})[_d = id || "__internal_without_id"]) != null ? _e : _c[_d] = [];
+              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
+              if (!alreadySubscribed) {
+                subscribedQueries.push(queryCacheKey);
+              }
+            }
+            draft.keys[queryCacheKey] = providedTags;
+          }
+        },
+        prepare: prepareAutoBatched()
+      }
+    },
+    extraReducers(builder) {
+      builder.addCase(querySlice.actions.removeQueryResult, (draft, {
+        payload: {
+          queryCacheKey
+        }
+      }) => {
+        removeCacheKeyFromTags(draft, queryCacheKey);
+      }).addMatcher(hasRehydrationInfo, (draft, action) => {
+        var _a, _b, _c, _d, _e, _f;
+        const {
+          provided
+        } = extractRehydrationInfo(action);
+        for (const [type, incomingTags] of Object.entries((_a = provided.tags) != null ? _a : {})) {
+          for (const [id, cacheKeys] of Object.entries(incomingTags)) {
+            const subscribedQueries = (_f = (_d = (_c = (_b = draft.tags)[type]) != null ? _c : _b[type] = {})[_e = id || "__internal_without_id"]) != null ? _f : _d[_e] = [];
+            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 = action.payload.map(({
+          queryDescription,
+          value
+        }) => {
+          return {
+            type: "UNKNOWN",
+            payload: value,
+            meta: {
+              requestStatus: "fulfilled",
+              requestId: "UNKNOWN",
+              arg: queryDescription
+            }
+          };
+        });
+        writeProvidedTagsForQueries(draft, mockActions);
+      });
+    }
+  });
+  function removeCacheKeyFromTags(draft, queryCacheKey) {
+    var _a, _b, _c;
+    const existingTags = getCurrent((_a = draft.keys[queryCacheKey]) != null ? _a : []);
+    for (const tag of existingTags) {
+      const tagType = tag.type;
+      const tagId = (_b = tag.id) != null ? _b : "__internal_without_id";
+      const tagSubscriptions = (_c = draft.tags[tagType]) == null ? void 0 : _c[tagId];
+      if (tagSubscriptions) {
+        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter((qc) => qc !== queryCacheKey);
+      }
+    }
+    delete draft.keys[queryCacheKey];
+  }
+  function writeProvidedTagsForQueries(draft, actions3) {
+    const providedByEntries = actions3.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));
+  }
+  const subscriptionSlice = createSlice({
+    name: `${reducerPath}/subscriptions`,
+    initialState,
+    reducers: {
+      updateSubscriptionOptions(d, a) {
+      },
+      unsubscribeQueryResult(d, a) {
+      },
+      internal_getRTKQSubscriptions() {
+      }
+    }
+  });
+  const internalSubscriptionsSlice = createSlice({
+    name: `${reducerPath}/internalSubscriptions`,
+    initialState,
+    reducers: {
+      subscriptionsUpdated: {
+        reducer(state, action) {
+          return applyPatches(state, action.payload);
+        },
+        prepare: prepareAutoBatched()
+      }
+    }
+  });
+  const configSlice = createSlice({
+    name: `${reducerPath}/config`,
+    initialState: __spreadValues({
+      online: isOnline(),
+      focused: isDocumentVisible(),
+      middlewareRegistered: false
+    }, config),
+    reducers: {
+      middlewareRegistered(state, {
+        payload
+      }) {
+        state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
+      }
+    },
+    extraReducers: (builder) => {
+      builder.addCase(onOnline, (state) => {
+        state.online = true;
+      }).addCase(onOffline, (state) => {
+        state.online = false;
+      }).addCase(onFocus, (state) => {
+        state.focused = true;
+      }).addCase(onFocusLost, (state) => {
+        state.focused = false;
+      }).addMatcher(hasRehydrationInfo, (draft) => __spreadValues({}, draft));
+    }
+  });
+  const combinedReducer = combineReducers({
+    queries: querySlice.reducer,
+    mutations: mutationSlice.reducer,
+    provided: invalidationSlice.reducer,
+    subscriptions: internalSubscriptionsSlice.reducer,
+    config: configSlice.reducer
+  });
+  const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
+  const actions2 = __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, configSlice.actions), querySlice.actions), subscriptionSlice.actions), internalSubscriptionsSlice.actions), mutationSlice.actions), invalidationSlice.actions), {
+    resetApiState
+  });
+  return {
+    reducer,
+    actions: actions2
+  };
+}
+
+// src/query/core/buildSelectors.ts
+var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
+var initialSubState = {
+  status: STATUS_UNINITIALIZED
+};
+var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => {
+});
+var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, () => {
+});
+function buildSelectors({
+  serializeQueryArgs,
+  reducerPath,
+  createSelector: createSelector2
+}) {
+  const selectSkippedQuery = (state) => defaultQuerySubState;
+  const selectSkippedMutation = (state) => defaultMutationSubState;
+  return {
+    buildQuerySelector,
+    buildInfiniteQuerySelector,
+    buildMutationSelector,
+    selectInvalidatedBy,
+    selectCachedArgsForQuery,
+    selectApiState,
+    selectQueries,
+    selectMutations,
+    selectQueryEntry,
+    selectConfig
+  };
+  function withRequestFlags(substate) {
+    return __spreadValues(__spreadValues({}, substate), getRequestStatusFlags(substate.status));
+  }
+  function selectApiState(rootState) {
+    const state = rootState[reducerPath];
+    if (process.env.NODE_ENV !== "production") {
+      if (!state) {
+        if (selectApiState.triggered) return state;
+        selectApiState.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) {
+    var _a;
+    return (_a = selectApiState(rootState)) == null ? void 0 : _a.queries;
+  }
+  function selectQueryEntry(rootState, cacheKey) {
+    var _a;
+    return (_a = selectQueries(rootState)) == null ? void 0 : _a[cacheKey];
+  }
+  function selectMutations(rootState) {
+    var _a;
+    return (_a = selectApiState(rootState)) == null ? void 0 : _a.mutations;
+  }
+  function selectConfig(rootState) {
+    var _a;
+    return (_a = selectApiState(rootState)) == null ? void 0 : _a.config;
+  }
+  function buildAnyQuerySelector(endpointName, endpointDefinition, combiner) {
+    return (queryArgs) => {
+      if (queryArgs === skipToken) {
+        return createSelector2(selectSkippedQuery, combiner);
+      }
+      const serializedArgs = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      });
+      const selectQuerySubstate = (state) => {
+        var _a;
+        return (_a = selectQueryEntry(state, serializedArgs)) != null ? _a : defaultQuerySubState;
+      };
+      return createSelector2(selectQuerySubstate, combiner);
+    };
+  }
+  function buildQuerySelector(endpointName, endpointDefinition) {
+    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags);
+  }
+  function buildInfiniteQuerySelector(endpointName, endpointDefinition) {
+    const {
+      infiniteQueryOptions
+    } = endpointDefinition;
+    function withInfiniteQueryResultFlags(substate) {
+      const stateWithRequestFlags = __spreadValues(__spreadValues({}, substate), getRequestStatusFlags(substate.status));
+      const {
+        isLoading,
+        isError,
+        direction
+      } = stateWithRequestFlags;
+      const isForward = direction === "forward";
+      const isBackward = direction === "backward";
+      return __spreadProps(__spreadValues({}, 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);
+  }
+  function buildMutationSelector() {
+    return (id) => {
+      var _a;
+      let mutationId;
+      if (typeof id === "object") {
+        mutationId = (_a = getMutationCacheKey(id)) != null ? _a : skipToken;
+      } else {
+        mutationId = id;
+      }
+      const selectMutationSubstate = (state) => {
+        var _a2, _b, _c;
+        return (_c = (_b = (_a2 = selectApiState(state)) == null ? void 0 : _a2.mutations) == null ? void 0 : _b[mutationId]) != null ? _c : defaultMutationSubState;
+      };
+      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
+      return createSelector2(finalSelectMutationSubstate, withRequestFlags);
+    };
+  }
+  function selectInvalidatedBy(state, tags) {
+    var _a;
+    const apiState = state[reducerPath];
+    const toInvalidate = /* @__PURE__ */ new Set();
+    const finalTags = filterMap(tags, isNotNullish, expandTagDescription);
+    for (const tag of finalTags) {
+      const provided = apiState.provided.tags[tag.type];
+      if (!provided) {
+        continue;
+      }
+      let invalidateSubscriptions = (_a = tag.id !== void 0 ? (
+        // id given: invalidate all queries that provide this type & id
+        provided[tag.id]
+      ) : (
+        // no id: invalidate all queries that provide this type
+        Object.values(provided).flat()
+      )) != null ? _a : [];
+      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(state, queryName) {
+    return filterMap(Object.values(selectQueries(state)), (entry) => (entry == null ? void 0 : entry.endpointName) === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
+  }
+  function getHasNextPage(options, data, queryArg) {
+    if (!data) return false;
+    return getNextPageParam(options, data, queryArg) != null;
+  }
+  function getHasPreviousPage(options, data, queryArg) {
+    if (!data || !options.getPreviousPageParam) return false;
+    return getPreviousPageParam(options, data, queryArg) != null;
+  }
+}
+
+// src/query/createApi.ts
+import { formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage22, formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
+
+// src/query/defaultSerializeQueryArgs.ts
+var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
+var defaultSerializeQueryArgs = ({
+  endpointName,
+  queryArgs
+}) => {
+  let serialized = "";
+  const cached = cache == null ? void 0 : cache.get(queryArgs);
+  if (typeof cached === "string") {
+    serialized = cached;
+  } else {
+    const stringified = JSON.stringify(queryArgs, (key, value) => {
+      value = typeof value === "bigint" ? {
+        $bigint: value.toString()
+      } : value;
+      value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
+        acc[key2] = value[key2];
+        return acc;
+      }, {}) : value;
+      return value;
+    });
+    if (isPlainObject(queryArgs)) {
+      cache == null ? void 0 : cache.set(queryArgs, stringified);
+    }
+    serialized = stringified;
+  }
+  return `${endpointName}(${serialized})`;
+};
+
+// src/query/createApi.ts
+import { weakMapMemoize } from "reselect";
+function buildCreateApi(...modules) {
+  return function baseCreateApi(options) {
+    const extractRehydrationInfo = weakMapMemoize((action) => {
+      var _a, _b;
+      return (_b = options.extractRehydrationInfo) == null ? void 0 : _b.call(options, action, {
+        reducerPath: (_a = options.reducerPath) != null ? _a : "api"
+      });
+    });
+    const optionsWithDefaults = __spreadProps(__spreadValues({
+      reducerPath: "api",
+      keepUnusedDataFor: 60,
+      refetchOnMountOrArgChange: false,
+      refetchOnFocus: false,
+      refetchOnReconnect: false,
+      invalidationBehavior: "delayed"
+    }, options), {
+      extractRehydrationInfo,
+      serializeQueryArgs(queryArgsApi) {
+        let finalSerializeQueryArgs = defaultSerializeQueryArgs;
+        if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
+          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
+          finalSerializeQueryArgs = (queryArgsApi2) => {
+            const initialResult = endpointSQA(queryArgsApi2);
+            if (typeof initialResult === "string") {
+              return initialResult;
+            } else {
+              return defaultSerializeQueryArgs(__spreadProps(__spreadValues({}, queryArgsApi2), {
+                queryArgs: initialResult
+              }));
+            }
+          };
+        } else if (options.serializeQueryArgs) {
+          finalSerializeQueryArgs = options.serializeQueryArgs;
+        }
+        return finalSerializeQueryArgs(queryArgsApi);
+      },
+      tagTypes: [...options.tagTypes || []]
+    });
+    const context = {
+      endpointDefinitions: {},
+      batch(fn) {
+        fn();
+      },
+      apiUid: nanoid(),
+      extractRehydrationInfo,
+      hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null)
+    };
+    const api = {
+      injectEndpoints,
+      enhanceEndpoints({
+        addTagTypes,
+        endpoints
+      }) {
+        if (addTagTypes) {
+          for (const eT of addTagTypes) {
+            if (!optionsWithDefaults.tagTypes.includes(eT)) {
+              ;
+              optionsWithDefaults.tagTypes.push(eT);
+            }
+          }
+        }
+        if (endpoints) {
+          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
+            if (typeof partialDefinition === "function") {
+              partialDefinition(getEndpointDefinition(context, endpointName));
+            } else {
+              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
+            }
+          }
+        }
+        return api;
+      }
+    };
+    const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
+    function injectEndpoints(inject) {
+      const evaluatedEndpoints = inject.endpoints({
+        query: (x) => __spreadProps(__spreadValues({}, x), {
+          type: ENDPOINT_QUERY
+        }),
+        mutation: (x) => __spreadProps(__spreadValues({}, x), {
+          type: ENDPOINT_MUTATION
+        }),
+        infiniteQuery: (x) => __spreadProps(__spreadValues({}, x), {
+          type: ENDPOINT_INFINITEQUERY
+        })
+      });
+      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
+        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
+          if (inject.overrideExisting === "throw") {
+            throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(39) : `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: getPreviousPageParam2
+            } = infiniteQueryOptions;
+            if (typeof maxPages === "number") {
+              if (maxPages < 1) {
+                throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage22(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);
+              }
+              if (typeof getPreviousPageParam2 !== "function") {
+                throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(41) : `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;
+    }
+    return api.injectEndpoints({
+      endpoints: options.endpoints
+    });
+  };
+}
+
+// src/query/fakeBaseQuery.ts
+import { formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
+var _NEVER = /* @__PURE__ */ Symbol();
+function fakeBaseQuery() {
+  return function() {
+    throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
+  };
+}
+
+// src/query/tsHelpers.ts
+function assertCast(v) {
+}
+function safeAssign(target, ...args) {
+  return Object.assign(target, ...args);
+}
+
+// src/query/core/buildMiddleware/batchActions.ts
+var buildBatchedActionsHandler = ({
+  api,
+  queryThunk,
+  internalState,
+  mwApi
+}) => {
+  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
+  let previousSubscriptions = null;
+  let updateSyncTimer = null;
+  const {
+    updateSubscriptionOptions,
+    unsubscribeQueryResult
+  } = api.internalActions;
+  const actuallyMutateSubscriptions = (currentSubscriptions, action) => {
+    var _a, _b, _c, _d;
+    if (updateSubscriptionOptions.match(action)) {
+      const {
+        queryCacheKey,
+        requestId,
+        options
+      } = action.payload;
+      const sub = currentSubscriptions.get(queryCacheKey);
+      if (sub == null ? void 0 : 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, (_b = (_a = arg.subscriptionOptions) != null ? _a : substate.get(requestId)) != null ? _b : {});
+      }
+      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, (_d = (_c = arg.subscriptionOptions) != null ? _c : substate.get(requestId)) != null ? _d : {});
+        mutated = true;
+      }
+    }
+    return mutated;
+  };
+  const getSubscriptions = () => internalState.currentSubscriptions;
+  const getSubscriptionCount = (queryCacheKey) => {
+    var _a;
+    const subscriptions = getSubscriptions();
+    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);
+    return (_a = subscriptionsForQueryArg == null ? void 0 : subscriptionsForQueryArg.size) != null ? _a : 0;
+  };
+  const isRequestSubscribed = (queryCacheKey, requestId) => {
+    var _a;
+    const subscriptions = getSubscriptions();
+    return !!((_a = subscriptions == null ? void 0 : subscriptions.get(queryCacheKey)) == null ? void 0 : _a.get(requestId));
+  };
+  const subscriptionSelectors = {
+    getSubscriptions,
+    getSubscriptionCount,
+    isRequestSubscribed
+  };
+  function serializeSubscriptions(currentSubscriptions) {
+    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));
+  }
+  return (action, mwApi2) => {
+    if (!previousSubscriptions) {
+      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
+    }
+    if (api.util.resetApiState.match(action)) {
+      previousSubscriptions = {};
+      internalState.currentSubscriptions.clear();
+      updateSyncTimer = null;
+      return [true, false];
+    }
+    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
+      return [false, subscriptionSelectors];
+    }
+    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
+    let actionShouldContinue = true;
+    if (process.env.NODE_ENV === "test" && typeof action.type === "string" && action.type === `${api.reducerPath}/getPolling`) {
+      return [false, internalState.currentPolls];
+    }
+    if (didMutate) {
+      if (!updateSyncTimer) {
+        updateSyncTimer = setTimeout(() => {
+          const newSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
+          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);
+          mwApi2.next(api.internalActions.subscriptionsUpdated(patches));
+          previousSubscriptions = newSubscriptions;
+          updateSyncTimer = null;
+        }, 500);
+      }
+      const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
+      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
+      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
+    }
+    return [actionShouldContinue, false];
+  };
+};
+
+// src/query/core/buildMiddleware/cacheCollection.ts
+var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
+var buildCacheCollectionHandler = ({
+  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) {
+    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);
+    if (!subscriptions) {
+      return false;
+    }
+    const hasSubscriptions = subscriptions.size > 0;
+    return hasSubscriptions;
+  }
+  const currentRemovalTimeouts = {};
+  function abortAllPromises(promiseMap) {
+    var _a;
+    for (const promise of promiseMap.values()) {
+      (_a = promise == null ? void 0 : promise.abort) == null ? void 0 : _a.call(promise);
+    }
+  }
+  const handler = (action, mwApi2) => {
+    const state = mwApi2.getState();
+    const config = selectConfig(state);
+    if (canTriggerUnsubscribe(action)) {
+      let queryCacheKeys;
+      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, mwApi2, 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);
+      handleUnsubscribeMany(Object.keys(queries), mwApi2, config);
+    }
+  };
+  function handleUnsubscribeMany(cacheKeys, api2, config) {
+    const state = api2.getState();
+    for (const queryCacheKey of cacheKeys) {
+      const entry = selectQueryEntry(state, queryCacheKey);
+      if (entry == null ? void 0 : entry.endpointName) {
+        handleUnsubscribe(queryCacheKey, entry.endpointName, api2, config);
+      }
+    }
+  }
+  function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
+    var _a;
+    const endpointDefinition = getEndpointDefinition(context, endpointName);
+    const keepUnusedDataFor = (_a = endpointDefinition == null ? void 0 : endpointDefinition.keepUnusedDataFor) != null ? _a : config.keepUnusedDataFor;
+    if (keepUnusedDataFor === Infinity) {
+      return;
+    }
+    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
+    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+      const currentTimeout = currentRemovalTimeouts[queryCacheKey];
+      if (currentTimeout) {
+        clearTimeout(currentTimeout);
+      }
+      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
+        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+          const entry = selectQueryEntry(api2.getState(), queryCacheKey);
+          if (entry == null ? void 0 : entry.endpointName) {
+            const runningQuery = api2.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));
+            runningQuery == null ? void 0 : runningQuery.abort();
+          }
+          api2.dispatch(removeQueryResult({
+            queryCacheKey
+          }));
+        }
+        delete currentRemovalTimeouts[queryCacheKey];
+      }, finalKeepUnusedDataFor * 1e3);
+    }
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/cacheLifecycle.ts
+var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
+var buildCacheLifecycleHandler = ({
+  api,
+  reducerPath,
+  context,
+  queryThunk,
+  mutationThunk,
+  internalState,
+  selectors: {
+    selectQueryEntry,
+    selectApiState
+  }
+}) => {
+  const isQueryThunk = isAsyncThunkAction(queryThunk);
+  const isMutationThunk = isAsyncThunkAction(mutationThunk);
+  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
+  const lifecycleMap = {};
+  const {
+    removeQueryResult,
+    removeMutationResult,
+    cacheEntriesUpserted
+  } = api.internalActions;
+  function resolveLifecycleEntry(cacheKey, data, meta) {
+    const lifecycle = lifecycleMap[cacheKey];
+    if (lifecycle == null ? void 0 : lifecycle.valueResolved) {
+      lifecycle.valueResolved({
+        data,
+        meta
+      });
+      delete lifecycle.valueResolved;
+    }
+  }
+  function removeLifecycleEntry(cacheKey) {
+    const lifecycle = lifecycleMap[cacheKey];
+    if (lifecycle) {
+      delete lifecycleMap[cacheKey];
+      lifecycle.cacheEntryRemoved();
+    }
+  }
+  function getActionMetaFields(action) {
+    const {
+      arg,
+      requestId
+    } = action.meta;
+    const {
+      endpointName,
+      originalArgs
+    } = arg;
+    return [endpointName, originalArgs, requestId];
+  }
+  const handler = (action, mwApi, stateBefore) => {
+    const cacheKey = getCacheKey(action);
+    function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
+      const oldEntry = selectQueryEntry(stateBefore, cacheKey2);
+      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey2);
+      if (!oldEntry && newEntry) {
+        handleNewKey(endpointName, originalArgs, cacheKey2, 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 cacheKey2 of Object.keys(lifecycleMap)) {
+        removeLifecycleEntry(cacheKey2);
+      }
+    }
+  };
+  function getCacheKey(action) {
+    var _a;
+    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;
+    if (isMutationThunk(action)) {
+      return (_a = action.meta.arg.fixedCacheKey) != null ? _a : action.meta.requestId;
+    }
+    if (removeQueryResult.match(action)) return action.payload.queryCacheKey;
+    if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
+    return "";
+  }
+  function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName);
+    const onCacheEntryAdded = endpointDefinition == null ? void 0 : endpointDefinition.onCacheEntryAdded;
+    if (!onCacheEntryAdded) return;
+    const lifecycle = {};
+    const cacheEntryRemoved = new Promise((resolve) => {
+      lifecycle.cacheEntryRemoved = resolve;
+    });
+    const cacheDataLoaded = Promise.race([new Promise((resolve) => {
+      lifecycle.valueResolved = resolve;
+    }), cacheEntryRemoved.then(() => {
+      throw neverResolvedError;
+    })]);
+    cacheDataLoaded.catch(() => {
+    });
+    lifecycleMap[queryCacheKey] = lifecycle;
+    const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);
+    const extra = mwApi.dispatch((_, __, extra2) => extra2);
+    const lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {
+      getCacheEntry: () => selector(mwApi.getState()),
+      requestId,
+      extra,
+      updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
+      cacheDataLoaded,
+      cacheEntryRemoved
+    });
+    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
+    Promise.resolve(runningHandler).catch((e) => {
+      if (e === neverResolvedError) return;
+      throw e;
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/devMiddleware.ts
+var buildDevCheckHandler = ({
+  api,
+  context: {
+    apiUid
+  },
+  reducerPath
+}) => {
+  return (action, mwApi) => {
+    var _a, _b;
+    if (api.util.resetApiState.match(action)) {
+      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
+    }
+    if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && ((_b = (_a = mwApi.getState()[reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered) === "conflict") {
+        console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
+You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
+      }
+    }
+  };
+};
+
+// src/query/core/buildMiddleware/invalidationByTags.ts
+var buildInvalidationByTagsHandler = ({
+  reducerPath,
+  context,
+  context: {
+    endpointDefinitions
+  },
+  mutationThunk,
+  queryThunk,
+  api,
+  assertTagType,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    removeQueryResult
+  } = api.internalActions;
+  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
+  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));
+  let pendingTagInvalidations = [];
+  let pendingRequestCount = 0;
+  const handler = (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, void 0, void 0, void 0, void 0, assertTagType), mwApi);
+    }
+  };
+  function hasPendingRequests() {
+    return pendingRequestCount > 0;
+  }
+  function invalidateTags(newTags, mwApi) {
+    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
+            }));
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            mwApi.dispatch(refetchQuery(querySubState));
+          }
+        }
+      }
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/polling.ts
+var buildPollingHandler = ({
+  reducerPath,
+  queryThunk,
+  api,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    currentPolls,
+    currentSubscriptions
+  } = internalState;
+  const pendingPollingUpdates = /* @__PURE__ */ new Set();
+  let pollingUpdateTimer = null;
+  const handler = (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();
+      if (pollingUpdateTimer) {
+        clearTimeout(pollingUpdateTimer);
+        pollingUpdateTimer = null;
+      }
+      pendingPollingUpdates.clear();
+    }
+  };
+  function schedulePollingUpdate(queryCacheKey, api2) {
+    pendingPollingUpdates.add(queryCacheKey);
+    if (!pollingUpdateTimer) {
+      pollingUpdateTimer = setTimeout(() => {
+        for (const key of pendingPollingUpdates) {
+          updatePollingInterval({
+            queryCacheKey: key
+          }, api2);
+        }
+        pendingPollingUpdates.clear();
+        pollingUpdateTimer = null;
+      }, 0);
+    }
+  }
+  function startNextPoll({
+    queryCacheKey
+  }, api2) {
+    const state = api2.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 == null ? void 0 : currentPoll.timeout) {
+      clearTimeout(currentPoll.timeout);
+      currentPoll.timeout = void 0;
+    }
+    const nextPollTimestamp = Date.now() + lowestPollingInterval;
+    currentPolls.set(queryCacheKey, {
+      nextPollTimestamp,
+      pollingInterval: lowestPollingInterval,
+      timeout: setTimeout(() => {
+        if (state.config.focused || !skipPollingIfUnfocused) {
+          api2.dispatch(refetchQuery(querySubState));
+        }
+        startNextPoll({
+          queryCacheKey
+        }, api2);
+      }, lowestPollingInterval)
+    });
+  }
+  function updatePollingInterval({
+    queryCacheKey
+  }, api2) {
+    var _a, _b;
+    const state = api2.getState()[reducerPath];
+    const querySubState = state.queries[queryCacheKey];
+    const subscriptions = currentSubscriptions.get(queryCacheKey);
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
+      return;
+    }
+    const {
+      lowestPollingInterval
+    } = findLowestPollingInterval(subscriptions);
+    if (process.env.NODE_ENV === "test") {
+      const updateCounters = (_a = currentPolls.pollUpdateCounters) != null ? _a : currentPolls.pollUpdateCounters = {};
+      (_b = updateCounters[queryCacheKey]) != null ? _b : 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
+      }, api2);
+    }
+  }
+  function cleanupPollForKey(key) {
+    const existingPoll = currentPolls.get(key);
+    if (existingPoll == null ? void 0 : existingPoll.timeout) {
+      clearTimeout(existingPoll.timeout);
+    }
+    currentPolls.delete(key);
+  }
+  function clearPolls() {
+    for (const key of currentPolls.keys()) {
+      cleanupPollForKey(key);
+    }
+  }
+  function findLowestPollingInterval(subscribers = /* @__PURE__ */ new Map()) {
+    let skipPollingIfUnfocused = 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;
+};
+
+// src/query/core/buildMiddleware/queryLifecycle.ts
+var buildQueryLifecycleHandler = ({
+  api,
+  context,
+  queryThunk,
+  mutationThunk
+}) => {
+  const isPendingThunk = isPending(queryThunk, mutationThunk);
+  const isRejectedThunk = isRejected(queryThunk, mutationThunk);
+  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);
+  const lifecycleMap = {};
+  const handler = (action, mwApi) => {
+    var _a, _b, _c;
+    if (isPendingThunk(action)) {
+      const {
+        requestId,
+        arg: {
+          endpointName,
+          originalArgs
+        }
+      } = action.meta;
+      const endpointDefinition = getEndpointDefinition(context, endpointName);
+      const onQueryStarted = endpointDefinition == null ? void 0 : endpointDefinition.onQueryStarted;
+      if (onQueryStarted) {
+        const lifecycle = {};
+        const queryFulfilled = new Promise((resolve, reject) => {
+          lifecycle.resolve = resolve;
+          lifecycle.reject = reject;
+        });
+        queryFulfilled.catch(() => {
+        });
+        lifecycleMap[requestId] = lifecycle;
+        const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);
+        const extra = mwApi.dispatch((_, __, extra2) => extra2);
+        const lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {
+          getCacheEntry: () => selector(mwApi.getState()),
+          requestId,
+          extra,
+          updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
+          queryFulfilled
+        });
+        onQueryStarted(originalArgs, lifecycleApi);
+      }
+    } else if (isFullfilledThunk(action)) {
+      const {
+        requestId,
+        baseQueryMeta
+      } = action.meta;
+      (_a = lifecycleMap[requestId]) == null ? void 0 : _a.resolve({
+        data: action.payload,
+        meta: baseQueryMeta
+      });
+      delete lifecycleMap[requestId];
+    } else if (isRejectedThunk(action)) {
+      const {
+        requestId,
+        rejectedWithValue,
+        baseQueryMeta
+      } = action.meta;
+      (_c = lifecycleMap[requestId]) == null ? void 0 : _c.reject({
+        error: (_b = action.payload) != null ? _b : action.error,
+        isUnhandledError: !rejectedWithValue,
+        meta: baseQueryMeta
+      });
+      delete lifecycleMap[requestId];
+    }
+  };
+  return handler;
+};
+
+// src/query/core/buildMiddleware/windowEventHandling.ts
+var buildWindowEventHandler = ({
+  reducerPath,
+  context,
+  api,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    removeQueryResult
+  } = api.internalActions;
+  const handler = (action, mwApi) => {
+    if (onFocus.match(action)) {
+      refetchValidQueries(mwApi, "refetchOnFocus");
+    }
+    if (onOnline.match(action)) {
+      refetchValidQueries(mwApi, "refetchOnReconnect");
+    }
+  };
+  function refetchValidQueries(api2, type) {
+    const state = api2.getState()[reducerPath];
+    const queries = state.queries;
+    const subscriptions = internalState.currentSubscriptions;
+    context.batch(() => {
+      for (const queryCacheKey of 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] === void 0) && state.config[type];
+        if (shouldRefetch) {
+          if (subscriptionSubState.size === 0) {
+            api2.dispatch(removeQueryResult({
+              queryCacheKey
+            }));
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            api2.dispatch(refetchQuery(querySubState));
+          }
+        }
+      }
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/index.ts
+function buildMiddleware(input) {
+  const {
+    reducerPath,
+    queryThunk,
+    api,
+    context,
+    getInternalState
+  } = input;
+  const {
+    apiUid
+  } = context;
+  const actions2 = {
+    invalidateTags: createAction(`${reducerPath}/invalidateTags`)
+  };
+  const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
+  const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
+  const middleware = (mwApi) => {
+    let initialized2 = false;
+    const internalState = getInternalState(mwApi.dispatch);
+    const builderArgs = __spreadProps(__spreadValues({}, input), {
+      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 (!initialized2) {
+          initialized2 = true;
+          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
+        }
+        const mwApiWithNext = __spreadProps(__spreadValues({}, mwApi), {
+          next
+        });
+        const stateBefore = mwApi.getState();
+        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
+        let res;
+        if (actionShouldContinue) {
+          res = next(action);
+        } else {
+          res = internalProbeResult;
+        }
+        if (!!mwApi.getState()[reducerPath]) {
+          windowEventsHandler(action, mwApiWithNext, stateBefore);
+          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
+            for (const handler of handlers) {
+              handler(action, mwApiWithNext, stateBefore);
+            }
+          }
+        }
+        return res;
+      };
+    };
+  };
+  return {
+    middleware,
+    actions: actions2
+  };
+  function refetchQuery(querySubState) {
+    return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
+      subscribe: false,
+      forceRefetch: true
+    });
+  }
+}
+
+// src/query/core/module.ts
+var coreModuleName = /* @__PURE__ */ Symbol();
+var coreModule = ({
+  createSelector: createSelector2 = createSelector
+} = {}) => ({
+  name: coreModuleName,
+  init(api, {
+    baseQuery,
+    tagTypes,
+    reducerPath,
+    serializeQueryArgs,
+    keepUnusedDataFor,
+    refetchOnMountOrArgChange,
+    refetchOnFocus,
+    refetchOnReconnect,
+    invalidationBehavior,
+    onSchemaFailure,
+    catchSchemaFailure,
+    skipSchemaValidation
+  }, context) {
+    enablePatches();
+    assertCast(serializeQueryArgs);
+    const assertTagType = (tag) => {
+      if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+        if (!tagTypes.includes(tag.type)) {
+          console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
+        }
+      }
+      return tag;
+    };
+    Object.assign(api, {
+      reducerPath,
+      endpoints: {},
+      internalActions: {
+        onOnline,
+        onOffline,
+        onFocus,
+        onFocusLost
+      },
+      util: {}
+    });
+    const selectors = buildSelectors({
+      serializeQueryArgs,
+      reducerPath,
+      createSelector: createSelector2
+    });
+    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
+    });
+    safeAssign(api.internalActions, sliceActions);
+    const internalStateMap = /* @__PURE__ */ new WeakMap();
+    const getInternalState = (dispatch) => {
+      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
+        currentSubscriptions: /* @__PURE__ */ new Map(),
+        currentPolls: /* @__PURE__ */ new Map(),
+        runningQueries: /* @__PURE__ */ new Map(),
+        runningMutations: /* @__PURE__ */ new Map()
+      }));
+      return state;
+    };
+    const {
+      buildInitiateQuery,
+      buildInitiateInfiniteQuery,
+      buildInitiateMutation,
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueriesThunk,
+      getRunningQueryThunk
+    } = buildInitiate({
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      serializeQueryArgs,
+      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,
+      middleware
+    });
+    return {
+      name: coreModuleName,
+      injectEndpoint(endpointName, definition) {
+        var _a, _b;
+        const anyApi = api;
+        const endpoint = (_b = (_a = anyApi.endpoints)[endpointName]) != null ? _b : _a[endpointName] = {};
+        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));
+        }
+      }
+    };
+  }
+});
+
+// src/query/core/index.ts
+var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
+export {
+  NamedSchemaError,
+  QueryStatus,
+  _NEVER,
+  buildCreateApi,
+  copyWithStructuralSharing,
+  coreModule,
+  coreModuleName,
+  createApi,
+  defaultSerializeQueryArgs,
+  fakeBaseQuery,
+  fetchBaseQuery,
+  retry,
+  setupListeners,
+  skipToken
+};
+//# sourceMappingURL=rtk-query.legacy-esm.js.map
Index: node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/query/core/apiState.ts","../../src/query/core/rtkImports.ts","../../src/query/utils/copyWithStructuralSharing.ts","../../src/query/utils/filterMap.ts","../../src/query/utils/isAbsoluteUrl.ts","../../src/query/utils/isDocumentVisible.ts","../../src/query/utils/isNotNullish.ts","../../src/query/utils/isOnline.ts","../../src/query/utils/joinUrls.ts","../../src/query/utils/getOrInsert.ts","../../src/query/utils/signals.ts","../../src/query/fetchBaseQuery.ts","../../src/query/HandledError.ts","../../src/query/retry.ts","../../src/query/core/setupListeners.ts","../../src/query/endpointDefinitions.ts","../../src/query/utils/immerImports.ts","../../src/query/core/buildInitiate.ts","../../src/tsHelpers.ts","../../src/query/apiTypes.ts","../../src/query/standardSchema.ts","../../src/query/core/buildThunks.ts","../../src/query/utils/getCurrent.ts","../../src/query/core/buildSlice.ts","../../src/query/core/buildSelectors.ts","../../src/query/createApi.ts","../../src/query/defaultSerializeQueryArgs.ts","../../src/query/fakeBaseQuery.ts","../../src/query/tsHelpers.ts","../../src/query/core/buildMiddleware/batchActions.ts","../../src/query/core/buildMiddleware/cacheCollection.ts","../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../src/query/core/buildMiddleware/devMiddleware.ts","../../src/query/core/buildMiddleware/invalidationByTags.ts","../../src/query/core/buildMiddleware/polling.ts","../../src/query/core/buildMiddleware/queryLifecycle.ts","../../src/query/core/buildMiddleware/windowEventHandling.ts","../../src/query/core/buildMiddleware/index.ts","../../src/query/core/module.ts","../../src/query/core/index.ts"],"sourcesContent":["import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, FullTagDescription, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFromAnyQuery, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n  _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n  queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n  requestId: string;\n  fixedCacheKey?: string;\n} | {\n  requestId?: string;\n  fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number;\n  refetchOnReconnect: boolean;\n  refetchOnFocus: boolean;\n};\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam;\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (lastPage: DataType, allPages: Array<DataType>, lastPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>;\n  pageParams: Array<PageParam>;\n};\n\n// NOTE: DO NOT import and use this for runtime comparisons internally,\n// except in the RTKQ React package. Use the string versions just below this.\n// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated\n// constants like \"initialized\":\n// https://github.com/evanw/esbuild/releases/tag/v0.14.7\n// We still have to use this in the React package since we don't publicly export\n// the string constants below.\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\n\n// Use these string constants for runtime comparisons internally\nexport const STATUS_UNINITIALIZED = QueryStatus.uninitialized;\nexport const STATUS_PENDING = QueryStatus.pending;\nexport const STATUS_FULFILLED = QueryStatus.fulfilled;\nexport const STATUS_REJECTED = QueryStatus.rejected;\nexport type RequestStatusFlags = {\n  status: QueryStatus.uninitialized;\n  isUninitialized: true;\n  isLoading: false;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.pending;\n  isUninitialized: false;\n  isLoading: true;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.fulfilled;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: true;\n  isError: false;\n} | {\n  status: QueryStatus.rejected;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: false;\n  isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === STATUS_UNINITIALIZED,\n    isLoading: status === STATUS_PENDING,\n    isSuccess: status === STATUS_FULFILLED,\n    isError: status === STATUS_REJECTED\n  } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\nexport type SubscribersInternal = Map<string, SubscriptionOptions>;\nexport type Subscribers = {\n  [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>;\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string;\n  /**\n   * The received data from the query\n   */\n  data?: DataType;\n  /**\n   * The received error if applicable\n   */\n  error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string;\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number;\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n  error: undefined;\n}) | ({\n  status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n  status: QueryStatus.uninitialized;\n  originalArgs?: undefined;\n  data?: undefined;\n  error?: undefined;\n  requestId?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n  direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = {\n  requestId: string;\n  data?: ResultTypeFrom<D>;\n  error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  endpointName: string;\n  startedTimeStamp: number;\n  fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = (({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n  error: undefined;\n}) | (({\n  status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n  data?: undefined;\n}) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n  requestId?: undefined;\n  status: QueryStatus.uninitialized;\n  data?: undefined;\n  error?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n  queries: QueryState<D>;\n  mutations: MutationState<D>;\n  provided: InvalidationState<E>;\n  subscriptions: SubscriptionState;\n  config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = {\n  tags: { [_ in TagTypes]: {\n    [id: string]: Array<QueryCacheKey>;\n    [id: number]: Array<QueryCacheKey>;\n  } };\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;\n};\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionInternalState = Map<string, SubscribersInternal>;\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath;\n  online: boolean;\n  focused: boolean;\n  middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number;\n  invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from '@reduxjs/toolkit';","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n    return newObj;\n  }\n  const newKeys = Object.keys(newObj);\n  const oldKeys = Object.keys(oldObj);\n  let isSameObject = newKeys.length === oldKeys.length;\n  const mergeObj: any = Array.isArray(newObj) ? [] : {};\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n  }\n  return isSameObject ? oldObj : mergeObj;\n}","// Preserve type guard predicate behavior when passing to mapper\nexport 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[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[] {\n  return array.reduce<(U | U[])[]>((acc, item, i) => {\n    if (predicate(item as any, i)) {\n      acc.push(mapper(item as any, i));\n    }\n    return acc;\n  }, []).flat() as U[];\n}","/**\n * If either :// or // is present consider it to be an absolute url\n *\n * @param url string\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url);\n}","/**\n * Assumes true for a non-browser env, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true;\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null;\n}\nexport function filterNullishValues<T>(map?: Map<any, T>) {\n  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[];\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n  if (!base) {\n    return url!;\n  }\n  if (!url) {\n    return base;\n  }\n  if (isAbsoluteUrl(url)) {\n    return url;\n  }\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n  base = withoutTrailingSlash(base);\n  url = withoutLeadingSlash(url);\n  return `${base}${delimiter}${url}`;\n}","// Duplicate some of the utils in `/src/utils` to ensure\n// we don't end up dragging in larger chunks of the RTK core\n// into the RTKQ bundle\n\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport const createNewMap = () => new Map();","// AbortSignal.timeout() is currently baseline 2024\nexport const timeoutSignal = (milliseconds: number) => {\n  const abortController = new AbortController();\n  setTimeout(() => {\n    const message = 'signal timed out';\n    const name = 'TimeoutError';\n    abortController.abort(\n    // some environments (React Native, Node) don't have DOMException\n    typeof DOMException !== 'undefined' ? new DOMException(message, name) : Object.assign(new Error(message), {\n      name\n    }));\n  }, milliseconds);\n  return abortController.signal;\n};\n\n// AbortSignal.any() is currently baseline 2024\nexport const anySignal = (...signals: AbortSignal[]) => {\n  // if any are already aborted, return an already aborted signal\n  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);\n\n  // otherwise, create a new signal that aborts when any of the given signals abort\n  const abortController = new AbortController();\n  for (const signal of signals) {\n    signal.addEventListener('abort', () => abortController.abort(signal.reason), {\n      signal: abortController.signal,\n      once: true\n    });\n  }\n  return abortController.signal;\n};","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nimport { anySignal, timeoutSignal } from './utils/signals';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n  headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n  url: string;\n  params?: Record<string, any>;\n  body?: any;\n  responseHandler?: ResponseHandler;\n  validateStatus?: (response: Response, body: any) => boolean;\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n  /**\n   * * `number`:\n   *   HTTP status code\n   */\n  status: number;\n  data: unknown;\n} | {\n  /**\n   * * `\"FETCH_ERROR\"`:\n   *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n   **/\n  status: 'FETCH_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"PARSING_ERROR\"`:\n   *   An error happened during parsing.\n   *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n   *   or an error occurred while executing a custom `responseHandler`.\n   **/\n  status: 'PARSING_ERROR';\n  originalStatus: number;\n  data: string;\n  error: string;\n} | {\n  /**\n   * * `\"TIMEOUT_ERROR\"`:\n   *   Request timed out\n   **/\n  status: 'TIMEOUT_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"CUSTOM_ERROR\"`:\n   *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n   **/\n  status: 'CUSTOM_ERROR';\n  data?: unknown;\n  error: string;\n};\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj;\n  }\n  const copy: Record<string, any> = {\n    ...obj\n  };\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k];\n  }\n  return copy;\n}\n\n// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\nconst isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string;\n  prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n    arg: string | FetchArgs;\n    extraOptions: unknown;\n  }) => MaybePromise<Headers | void>;\n  fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n  paramsSerializer?: (params: Record<string, any>) => string;\n  /**\n   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean;\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string;\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n  request: Request;\n  response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = x => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n  }\n  return async (arg, api, extraOptions) => {\n    const {\n      getState,\n      extra,\n      endpoint,\n      forced,\n      type\n    } = api;\n    let meta: FetchBaseQueryMeta | undefined;\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? 'json' as const,\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? {\n      url: arg\n    } : arg;\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,\n      ...rest\n    };\n    headers = new Headers(stripUndefined(headers));\n    config.headers = (await prepareHeaders(headers, {\n      getState,\n      arg,\n      extra,\n      endpoint,\n      forced,\n      type,\n      extraOptions\n    })) || headers;\n    const bodyIsJsonifiable = isJsonifiable(config.body);\n\n    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically\n    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)\n    if (config.body != null && !bodyIsJsonifiable && typeof config.body !== 'string') {\n      config.headers.delete('content-type');\n    }\n    if (!config.headers.has('content-type') && bodyIsJsonifiable) {\n      config.headers.set('content-type', jsonContentType);\n    }\n    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer);\n    }\n\n    // Set Accept header based on responseHandler if not already set\n    if (!config.headers.has('accept')) {\n      if (responseHandler === 'json') {\n        config.headers.set('accept', 'application/json');\n      } else if (responseHandler === 'text') {\n        config.headers.set('accept', 'text/plain, text/html, */*');\n      }\n      // For 'content-type' responseHandler, don't set Accept (let server decide)\n    }\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?';\n      const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n      url += divider + query;\n    }\n    url = joinUrls(baseUrl, url);\n    const request = new Request(url, config);\n    const requestClone = new Request(url, config);\n    meta = {\n      request: requestClone\n    };\n    let response;\n    try {\n      response = await fetchFn(request);\n    } catch (e) {\n      return {\n        error: {\n          status: (e instanceof Error || typeof DOMException !== 'undefined' && e instanceof DOMException) && e.name === 'TimeoutError' ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n          error: String(e)\n        },\n        meta\n      };\n    }\n    const responseClone = response.clone();\n    meta.response = responseClone;\n    let resultData: any;\n    let responseText: string = '';\n    try {\n      let handleResponseError;\n      await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n      // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n      // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n      responseClone.text().then(r => responseText = r, () => {})]);\n      if (handleResponseError) throw handleResponseError;\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e)\n        },\n        meta\n      };\n    }\n    return validateStatus(response, resultData) ? {\n      data: resultData,\n      meta\n    } : {\n      error: {\n        status: response.status,\n        data: resultData\n      },\n      meta\n    };\n  };\n  async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response);\n    }\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n    }\n    if (responseHandler === 'json') {\n      const text = await response.text();\n      return text.length ? JSON.parse(text) : null;\n    }\n    return response.text();\n  }\n}","export class HandledError {\n  constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5, signal?: AbortSignal) {\n  const attempts = Math.min(attempt, maxRetries);\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n\n  await new Promise<void>((resolve, reject) => {\n    const timeoutId = setTimeout(() => resolve(), timeout);\n\n    // If signal is provided and gets aborted, clear timeout and reject\n    if (signal) {\n      const abortHandler = () => {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      };\n\n      // Check if already aborted\n      if (signal.aborted) {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      } else {\n        signal.addEventListener('abort', abortHandler, {\n          once: true\n        });\n      }\n    }\n  });\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n  attempt: number;\n  baseQueryApi: BaseQueryApi;\n  extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (attempt: number, maxRetries: number, signal?: AbortSignal) => Promise<void>;\n} & ({\n  /**\n   * How many times the query will be retried (default: 5)\n   */\n  maxRetries?: number;\n  retryCondition?: undefined;\n} | {\n  /**\n   * Callback to determine if a retry should be attempted.\n   * Return `true` for another retry and `false` to quit trying prematurely.\n   */\n  retryCondition?: RetryConditionFunction;\n  maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n  throw Object.assign(new HandledError({\n    error,\n    meta\n  }), {\n    throwImmediately: true\n  });\n}\n\n/**\n * Checks if the abort signal is aborted and fails immediately if so.\n * Used to exit retry loops cleanly when a request is aborted.\n */\nfunction failIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    fail({\n      status: 'CUSTOM_ERROR',\n      error: 'Aborted'\n    });\n  }\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n  const [maxRetries] = possibleMaxRetries.slice(-1);\n  const defaultRetryCondition: RetryConditionFunction = (_, __, {\n    attempt\n  }) => attempt <= maxRetries;\n  const options: {\n    maxRetries: number;\n    backoff: typeof defaultBackoff;\n    retryCondition: typeof defaultRetryCondition;\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions\n  };\n  let retry = 0;\n  while (true) {\n    // Check if aborted before each attempt\n    failIfAborted(api.signal);\n    try {\n      const result = await baseQuery(args, api, extraOptions);\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result);\n      }\n      return result;\n    } catch (e: any) {\n      retry++;\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value;\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e;\n      }\n      if (e instanceof HandledError) {\n        if (!options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n          attempt: retry,\n          baseQueryApi: api,\n          extraOptions\n        })) {\n          return e.value; // Max retries for expected error\n        }\n      } else {\n        // For unexpected errors, respect maxRetries\n        if (retry > options.maxRetries) {\n          // Return the error as a proper error response instead of throwing\n          return {\n            error: e\n          };\n        }\n      }\n\n      // Check if aborted before backoff\n      failIfAborted(api.signal);\n      try {\n        await options.backoff(retry, options.maxRetries, api.signal);\n      } catch (backoffError) {\n        // If backoff was aborted, exit the retry loop\n        failIfAborted(api.signal);\n        // Otherwise, rethrow the backoff error\n        throw backoffError;\n      }\n    }\n  }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n  fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const INTERNAL_PREFIX = '__rtkq/';\nconst ONLINE = 'online';\nconst OFFLINE = 'offline';\nconst FOCUS = 'focus';\nconst FOCUSED = 'focused';\nconst VISIBILITYCHANGE = 'visibilitychange';\nexport const onFocus = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${FOCUSED}`);\nexport const onFocusLost = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);\nexport const onOnline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${ONLINE}`);\nexport const onOffline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${OFFLINE}`);\nconst actions = {\n  onFocus,\n  onFocusLost,\n  onOnline,\n  onOffline\n};\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n}) => () => void) {\n  function defaultHandler() {\n    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map(action => () => dispatch(action()));\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus();\n      } else {\n        handleFocusLost();\n      }\n    };\n    let unsubscribe = () => {\n      initialized = false;\n    };\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        const handlers = {\n          [FOCUS]: handleFocus,\n          [VISIBILITYCHANGE]: handleVisibilityChange,\n          [ONLINE]: handleOnline,\n          [OFFLINE]: handleOffline\n        };\n        function updateListeners(add: boolean) {\n          Object.entries(handlers).forEach(([event, handler]) => {\n            if (add) {\n              window.addEventListener(event, handler, false);\n            } else {\n              window.removeEventListener(event, handler);\n            }\n          });\n        }\n        // Handle focus events\n        updateListeners(true);\n        initialized = true;\n        unsubscribe = () => {\n          updateListeners(false);\n          initialized = false;\n        };\n      }\n    }\n    return unsubscribe;\n  }\n  return customHandler ? customHandler(dispatch, actions) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from 'immer';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { ENDPOINT_QUERY, isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { filterNullishValues } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n  [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\ntype RefetchOptions = {\n  refetchCachedPages?: boolean;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection;\n  param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>, InfiniteQueryArgFrom<D>>>, 'initialPageParam' | 'refetchCachedPages'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n  requestId: string;\n  subscriptionOptions: SubscriptionOptions | undefined;\n  abort(): void;\n  unsubscribe(): void;\n  updateSubscriptionOptions(options: SubscriptionOptions): void;\n  queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n  arg: any;\n  unwrap(): Promise<any>;\n  refetch(options?: RefetchOptions): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: QueryArgFrom<D>;\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: InfiniteQueryArgFrom<D>;\n  unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n  refetch(options?: Pick<StartInfiniteQueryActionCreatorOptions<D>, 'refetchCachedPages'>): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n  fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n  data: ResultTypeFrom<D>;\n  error?: undefined;\n} | {\n  data?: undefined;\n  error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string;\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>;\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean;\n    fixedCacheKey?: string;\n  };\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string;\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void;\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void;\n};\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context,\n  getInternalState\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  api: Api<any, EndpointDefinitions, any, any>;\n  context: ApiContext<EndpointDefinitions>;\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState;\n}) {\n  const getRunningQueries = (dispatch: Dispatch) => getInternalState(dispatch)?.runningQueries;\n  const getRunningMutations = (dispatch: Dispatch) => getInternalState(dispatch)?.runningMutations;\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions\n  } = api.internalActions;\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk\n  };\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      return getRunningQueries(dispatch)?.get(queryCacheKey) as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningMutationThunk(\n  /**\n   * this is only here to allow TS to infer the result type by input value\n   * we could use it to validate the result, but it's probably not necessary\n   */\n  _endpointName: string, fixedCacheKeyOrRequestId: string) {\n    return (dispatch: Dispatch) => {\n      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as MutationActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningQueries(dispatch));\n  }\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningMutations(dispatch));\n  }\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return;\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      (middlewareWarning as any).triggered = true;\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n        // Otherwise, must not have been added\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n      }\n    }\n  }\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n    const queryAction: AnyQueryActionCreator<any> = (arg, {\n      subscribe = true,\n      forceRefetch,\n      subscriptionOptions,\n      [forceQueryFnSymbol]: forceQueryFn,\n      ...rest\n    } = {}) => (dispatch, getState) => {\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName\n      });\n      let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n      const commonThunkArgs = {\n        ...rest,\n        type: ENDPOINT_QUERY as 'query',\n        subscribe,\n        forceRefetch: forceRefetch,\n        subscriptionOptions,\n        endpointName,\n        originalArgs: arg,\n        queryCacheKey,\n        [forceQueryFnSymbol]: forceQueryFn\n      };\n      if (isQueryDefinition(endpointDefinition)) {\n        thunk = queryThunk(commonThunkArgs);\n      } else {\n        const {\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam' | 'refetchCachedPages'>;\n        thunk = infiniteQueryThunk({\n          ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n          // Supply these even if undefined. This helps with a field existence\n          // check over in `buildSlice.ts`\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        });\n      }\n      const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n      const thunkResult = dispatch(thunk);\n      const stateAfter = selector(getState());\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort\n      } = thunkResult;\n      const skippedSynchronously = stateAfter.requestId !== requestId;\n      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);\n      const selectFromState = () => selector(getState());\n      const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n      // a query has been forced (upsertQueryData)\n      // -> we want to resolve it once data has been written with the data that will be written\n      thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n      // a query has been skipped due to a condition and we do not have any currently running query\n      // -> we want to resolve it immediately with the current data\n      Promise.resolve(stateAfter) :\n      // query just started or one is already in flight\n      // -> wait for the running query, then resolve with data from after that\n      Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n        arg,\n        requestId,\n        subscriptionOptions,\n        queryCacheKey,\n        abort,\n        async unwrap() {\n          const result = await statePromise;\n          if (result.isError) {\n            throw result.error;\n          }\n          return result.data;\n        },\n        refetch: (options?: RefetchOptions) => dispatch(queryAction(arg, {\n          subscribe: false,\n          forceRefetch: true,\n          ...options\n        })),\n        unsubscribe() {\n          if (subscribe) dispatch(unsubscribeQueryResult({\n            queryCacheKey,\n            requestId\n          }));\n        },\n        updateSubscriptionOptions(options: SubscriptionOptions) {\n          statePromise.subscriptionOptions = options;\n          dispatch(updateSubscriptionOptions({\n            endpointName,\n            requestId,\n            queryCacheKey,\n            options\n          }));\n        }\n      });\n      if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n        const runningQueries = getRunningQueries(dispatch)!;\n        runningQueries.set(queryCacheKey, statePromise);\n        statePromise.then(() => {\n          runningQueries.delete(queryCacheKey);\n        });\n      }\n      return statePromise;\n    };\n    return queryAction;\n  }\n  function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return queryAction;\n  }\n  function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return infiniteQueryAction;\n  }\n  function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n    return (arg, {\n      track = true,\n      fixedCacheKey\n    } = {}) => (dispatch, getState) => {\n      const thunk = mutationThunk({\n        type: 'mutation',\n        endpointName,\n        originalArgs: arg,\n        track,\n        fixedCacheKey\n      });\n      const thunkResult = dispatch(thunk);\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort,\n        unwrap\n      } = thunkResult;\n      const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n        data\n      })), error => ({\n        error\n      }));\n      const reset = () => {\n        dispatch(removeMutationResult({\n          requestId,\n          fixedCacheKey\n        }));\n      };\n      const ret = Object.assign(returnValuePromise, {\n        arg: thunkResult.arg,\n        requestId,\n        abort,\n        unwrap,\n        reset\n      });\n      const runningMutations = getRunningMutations(dispatch)!;\n      runningMutations.set(requestId, ret);\n      ret.then(() => {\n        runningMutations.delete(requestId);\n      });\n      if (fixedCacheKey) {\n        runningMutations.set(fixedCacheKey, ret);\n        ret.then(() => {\n          if (runningMutations.get(fixedCacheKey) === ret) {\n            runningMutations.delete(fixedCacheKey);\n          }\n        });\n      }\n      return ret;\n    };\n  }\n}","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn } from './baseQueryTypes';\nimport type { CombinedState, CoreModule, QueryKeys } from './core';\nimport type { ApiModules } from './core/module';\nimport type { CreateApiOptions } from './createApi';\nimport type { EndpointBuilder, EndpointDefinition, EndpointDefinitions, UpdateDefinitions } from './endpointDefinitions';\nimport type { NoInfer, UnionToIntersection, WithRequiredProp } from './tsHelpers';\nexport type ModuleName = keyof ApiModules<any, any, any, any>;\nexport type Module<Name extends ModuleName> = {\n  name: Name;\n  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>): {\n    injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;\n  };\n};\nexport interface ApiContext<Definitions extends EndpointDefinitions> {\n  apiUid: string;\n  endpointDefinitions: Definitions;\n  batch(cb: () => void): void;\n  extractRehydrationInfo: (action: UnknownAction) => CombinedState<any, any, any> | undefined;\n  hasRehydrationInfo: (action: UnknownAction) => boolean;\n}\nexport const getEndpointDefinition = <Definitions extends EndpointDefinitions, EndpointName extends keyof Definitions>(context: ApiContext<Definitions>, endpointName: EndpointName) => context.endpointDefinitions[endpointName];\nexport 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]> & {\n  /**\n   * 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.\n   */\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\n    endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;\n    /**\n     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n     *\n     * If set to `true`, will override existing endpoints with the new definition.\n     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n     */\n    overrideExisting?: boolean | 'throw';\n  }): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;\n  /**\n   *A function to enhance a generated API with additional information. Useful with code-generation.\n   */\n  enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {\n    addTagTypes?: readonly NewTagTypes[];\n    endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? { [K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void) } : never;\n  }): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;\n};","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { SchemaError } from '@standard-schema/utils';\nimport type { SchemaType } from './endpointDefinitions';\nexport class NamedSchemaError extends SchemaError {\n  constructor(issues: readonly StandardSchemaV1.Issue[], public readonly value: any, public readonly schemaName: `${SchemaType}Schema`, public readonly _bqMeta: any) {\n    super(issues);\n  }\n}\nexport const shouldSkip = (skipSchemaValidation: boolean | SchemaType[] | undefined, schemaName: SchemaType) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(schema: Schema, data: unknown, schemaName: `${SchemaType}Schema`, bqMeta: any): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data);\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);\n  }\n  return result.value;\n}","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from '../utils/immerImports';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultDescription, ResultTypeFrom, SchemaFailureConverter, SchemaFailureHandler, SchemaFailureInfo, SchemaType } from '../endpointDefinitions';\nimport { calculateProvidedBy, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nimport { parseWithSchema, NamedSchemaError, shouldSkip } from '../standardSchema';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>;\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n  type: 'query';\n  originalArgs: unknown;\n  endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n  type: `query`;\n  originalArgs: unknown;\n  endpointName: string;\n  param: unknown;\n  direction?: InfiniteQueryDirection;\n  refetchCachedPages?: boolean;\n};\ntype MutationThunkArg = {\n  type: 'mutation';\n  originalArgs: unknown;\n  endpointName: string;\n  track?: boolean;\n  fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n  pendingMeta: {\n    startedTimeStamp: number;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  fulfilledMeta: {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  rejectedMeta: {\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;\nexport type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;\nexport type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;\nexport type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;\nexport type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[];\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[];\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n  [SHOULD_AUTOBATCH]: true;\n} => {\n  return {\n    ...arg,\n    [SHOULD_AUTOBATCH]: true\n  };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n  reducerPath,\n  baseQuery,\n  context: {\n    endpointDefinitions\n  },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation\n}: {\n  baseQuery: BaseQuery;\n  reducerPath: ReducerPath;\n  context: ApiContext<Definitions>;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  api: Api<BaseQuery, Definitions, ReducerPath, any>;\n  assertTagType: AssertTagTypes;\n  selectors: AllSelectors;\n  onSchemaFailure: SchemaFailureHandler | undefined;\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined;\n  skipSchemaValidation: boolean | SchemaType[] | undefined;\n}) {\n  type State = RootState<any, string, ReducerPath>;\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n    const endpointDefinition = endpointDefinitions[endpointName];\n    const queryCacheKey = serializeQueryArgs({\n      queryArgs: arg,\n      endpointDefinition,\n      endpointName\n    });\n    dispatch(api.internalActions.queryResultPatched({\n      queryCacheKey,\n      patches\n    }));\n    if (!updateProvided) {\n      return;\n    }\n    const newValue = api.endpoints[endpointName].select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n    dispatch(api.internalActions.updateProvidedBy([{\n      queryCacheKey,\n      providedTags\n    }]));\n  };\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items];\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n  }\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item];\n    return max && newItems.length > max ? newItems.slice(1) : newItems;\n  }\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n    const endpointDefinition = api.endpoints[endpointName];\n    const currentState = endpointDefinition.select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const ret: PatchCollection = {\n      patches: [],\n      inversePatches: [],\n      undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n    };\n    if (currentState.status === STATUS_UNINITIALIZED) {\n      return ret;\n    }\n    let newValue;\n    if ('data' in currentState) {\n      if (isDraftable(currentState.data)) {\n        const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n        ret.patches.push(...patches);\n        ret.inversePatches.push(...inversePatches);\n        newValue = value;\n      } else {\n        newValue = updateRecipe(currentState.data);\n        ret.patches.push({\n          op: 'replace',\n          path: [],\n          value: newValue\n        });\n        ret.inversePatches.push({\n          op: 'replace',\n          path: [],\n          value: currentState.data\n        });\n      }\n    }\n    if (ret.patches.length === 0) {\n      return ret;\n    }\n    dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n    return ret;\n  };\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n    type EndpointName = typeof endpointName;\n    const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n      subscribe: false,\n      forceRefetch: true,\n      [forceQueryFnSymbol]: () => ({\n        data: value\n      })\n    })) as UpsertThunkResult<Definitions, EndpointName>;\n    return res;\n  };\n  const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n  };\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }> = async (arg, {\n    signal,\n    abort,\n    rejectWithValue,\n    fulfillWithValue,\n    dispatch,\n    getState,\n    extra\n  }) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName];\n    const {\n      metaSchema,\n      skipSchemaValidation = globalSkipSchemaValidation\n    } = endpointDefinition;\n    const isQuery = arg.type === ENDPOINT_QUERY;\n    try {\n      let transformResponse: TransformCallback = defaultTransformResponse;\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n      };\n      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined;\n      let finalQueryReturnValue: QueryReturnValue;\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({\n            data\n          });\n        }\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param\n        };\n        const pageResponse = await executeRequest(finalQueryArg);\n        const addTo = previous ? addToStart : addToEnd;\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages)\n          },\n          meta: pageResponse.meta\n        };\n      };\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n        let result: QueryReturnValue;\n        const {\n          extraOptions,\n          argSchema,\n          rawResponseSchema,\n          responseSchema\n        } = endpointDefinition;\n        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {\n          finalQueryArg = await parseWithSchema(argSchema, finalQueryArg, 'argSchema', {} // we don't have a meta yet, so we can't pass it\n          );\n        }\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn();\n        } else if (endpointDefinition.query) {\n          // We should only run `transformResponse` when the endpoint has a `query` method,\n          // and we're not doing an `upsertQueryData`.\n          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n          result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n        } else {\n          result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n          let err: undefined | string;\n          if (!result) {\n            err = `${what} did not return anything.`;\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`;\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`;\n                break;\n              }\n            }\n          }\n          if (err) {\n            console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`, result);\n          }\n        }\n        if (result.error) throw new HandledError(result.error, result.meta);\n        let {\n          data\n        } = result;\n        if (rawResponseSchema && !shouldSkip(skipSchemaValidation, 'rawResponse')) {\n          data = await parseWithSchema(rawResponseSchema, result.data, 'rawResponseSchema', result.meta);\n        }\n        let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);\n        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {\n          transformedResponse = await parseWithSchema(responseSchema, transformedResponse, 'responseSchema', result.meta);\n        }\n        return {\n          ...result,\n          data: transformedResponse\n        };\n      }\n      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const {\n          infiniteQueryOptions\n        } = endpointDefinition;\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const {\n          maxPages = Infinity\n        } = infiniteQueryOptions;\n\n        // Priority: per-call override > endpoint config > default (true)\n        const refetchCachedPages = (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;\n        let result: QueryReturnValue;\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = {\n          pages: [],\n          pageParams: []\n        };\n        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch =\n        // arg.forceRefetch\n        isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n        const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward';\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n          const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);\n          result = await fetchPage(existingData, param, maxPages, previous);\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const {\n            initialPageParam = infiniteQueryOptions.initialPageParam\n          } = arg as InfiniteQueryThunkArg<any>;\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? [];\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n          const totalPages = cachedPageParams.length;\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages);\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n            } as QueryReturnValue;\n          }\n          if (refetchCachedPages) {\n            // Fetch remaining pages\n            for (let i = 1; i < totalPages; i++) {\n              const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>, arg.originalArgs);\n              result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n            }\n          }\n        }\n        finalQueryReturnValue = result;\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs);\n      }\n      if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta') && finalQueryReturnValue.meta) {\n        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, 'metaSchema', finalQueryReturnValue.meta);\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n        fulfilledTimeStamp: Date.now(),\n        baseQueryMeta: finalQueryReturnValue.meta\n      }));\n    } catch (error) {\n      let caughtError = error;\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n        const {\n          rawErrorResponseSchema,\n          errorResponseSchema\n        } = endpointDefinition;\n        let {\n          value,\n          meta\n        } = caughtError;\n        try {\n          if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, 'rawErrorResponse')) {\n            value = await parseWithSchema(rawErrorResponseSchema, value, 'rawErrorResponseSchema', meta);\n          }\n          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta);\n          }\n          let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);\n          if (errorResponseSchema && !shouldSkip(skipSchemaValidation, 'errorResponse')) {\n            transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, 'errorResponseSchema', meta);\n          }\n          return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({\n            baseQueryMeta: meta\n          }));\n        } catch (e) {\n          caughtError = e;\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n          };\n          endpointDefinition.onSchemaFailure?.(caughtError, info);\n          onSchemaFailure?.(caughtError, info);\n          const {\n            catchSchemaFailure = globalCatchSchemaFailure\n          } = endpointDefinition;\n          if (catchSchemaFailure) {\n            return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({\n              baseQueryMeta: caughtError._bqMeta\n            }));\n          }\n        }\n      } catch (e) {\n        caughtError = e;\n      }\n      if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n        console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, caughtError);\n      } else {\n        console.error(caughtError);\n      }\n      throw caughtError;\n    }\n  };\n  function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n    const fulfilledVal = requestState?.fulfilledTimeStamp;\n    const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n    }\n    return false;\n  }\n  const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n    const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n      state: RootState<any, string, ReducerPath>;\n    }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({\n        arg\n      }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName];\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n            direction: (arg as InfiniteQueryThunkArg<any>).direction\n          } : {})\n        });\n      },\n      condition(queryThunkArg, {\n        getState\n      }) {\n        const state = getState();\n        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n        const fulfilledVal = requestState?.fulfilledTimeStamp;\n        const currentArg = queryThunkArg.originalArgs;\n        const previousArg = requestState?.originalArgs;\n        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true;\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false;\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true;\n        }\n        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n          currentArg,\n          previousArg,\n          endpointState: requestState,\n          state\n        })) {\n          return true;\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false;\n        }\n        return true;\n      },\n      dispatchConditionRejection: true\n    });\n    return generatedQueryThunk;\n  };\n  const queryThunk = createQueryThunk<QueryThunkArg>();\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n  const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({\n        startedTimeStamp: Date.now()\n      });\n    }\n  });\n  const hasTheForce = (options: any): options is {\n    force: boolean;\n  } => 'force' in options;\n  const hasMaxAge = (options: any): options is {\n    ifOlderThan: false | number;\n  } => 'ifOlderThan' in options;\n  const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions = {}): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n    const force = hasTheForce(options) && options.force;\n    const maxAge = hasMaxAge(options) && options.ifOlderThan;\n    const queryAction = (force: boolean = true) => {\n      const options: StartQueryActionCreatorOptions = {\n        forceRefetch: force,\n        subscribe: false\n      };\n      return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n    };\n    const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n    if (force) {\n      dispatch(queryAction());\n    } else if (maxAge) {\n      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n      if (!lastFulfilledTs) {\n        dispatch(queryAction());\n        return;\n      }\n      const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n      if (shouldRetrigger) {\n        dispatch(queryAction());\n      }\n    } else {\n      // If prefetching with no options, just let it try\n      dispatch(queryAction(false));\n    }\n  };\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n  }\n  function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n    } as Matchers<Thunk, any>;\n  }\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions\n  };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  const lastIndex = pages.length - 1;\n  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n  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);\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../utils/immerImports';\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}","import type { PayloadAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { STATUS_FULFILLED, STATUS_PENDING, QueryStatus, STATUS_REJECTED, STATUS_UNINITIALIZED } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { ENDPOINT_QUERY, isInfiniteQueryDefinition, type AssertTagTypes, type EndpointDefinitions, type FullTagDescription, type QueryDefinition } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { applyPatches, original, isDraft } from '../utils/immerImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport { getCurrent } from '../utils/getCurrent';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n  endpointName: EndpointName;\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string;\n  arg: unknown;\n  value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg;\n  value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n  const substate = state[queryCacheKey];\n  if (substate) {\n    update(substate);\n  }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n} | MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}, update: (substate: MutationSubState<any>) => void) {\n  const substate = state[getMutationCacheKey(id)];\n  if (substate) {\n    update(substate);\n  }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo\n  },\n  assertTagType,\n  config\n}: {\n  reducerPath: string;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  context: ApiContext<EndpointDefinitions>;\n  assertTagType: AssertTagTypes;\n  config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`);\n  function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n    // requestStatus: 'pending'\n  } & {\n    startedTimeStamp: number;\n  }) {\n    draft[arg.queryCacheKey] ??= {\n      status: STATUS_UNINITIALIZED,\n      endpointName: arg.endpointName\n    };\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n      substate.status = STATUS_PENDING;\n      substate.requestId = upserting && substate.requestId ?\n      // for `upsertQuery` **updates**, keep the current `requestId`\n      substate.requestId :\n      // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n      meta.requestId;\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs;\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp;\n      const endpointDefinition = definitions[meta.arg.endpointName];\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;\n        (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n      }\n    });\n  }\n  function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n  } & {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n  }, payload: unknown, upserting: boolean) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n      if (substate.requestId !== meta.requestId && !upserting) return;\n      const {\n        merge\n      } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n      substate.status = STATUS_FULFILLED;\n      if (merge) {\n        if (substate.data !== undefined) {\n          const {\n            fulfilledTimeStamp,\n            arg,\n            baseQueryMeta,\n            requestId\n          } = meta;\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, draftSubstateData => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId\n            });\n          });\n          substate.data = newData;\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload;\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n      }\n      delete substate.error;\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n    });\n  }\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey\n          }\n        }: PayloadAction<QuerySubstateIdentifier>) {\n          delete draft[queryCacheKey];\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n      },\n      cacheEntriesUpserted: {\n        reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n          RTK_autoBatch: boolean;\n          requestId: string;\n          timestamp: number;\n        }>) {\n          for (const entry of action.payload) {\n            const {\n              queryDescription: arg,\n              value\n            } = entry;\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp\n            });\n            writeFulfilledCacheEntry(draft, {\n              arg,\n              requestId: action.meta.requestId,\n              fulfilledTimeStamp: action.meta.timestamp,\n              baseQueryMeta: {}\n            }, value,\n            // We know we're upserting here\n            true);\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n            const {\n              endpointName,\n              arg,\n              value\n            } = entry;\n            const endpointDefinition = definitions[endpointName];\n            const queryDescription: QueryThunkArg = {\n              type: ENDPOINT_QUERY as 'query',\n              endpointName,\n              originalArgs: entry.arg,\n              queryCacheKey: serializeQueryArgs({\n                queryArgs: arg,\n                endpointDefinition,\n                endpointName\n              })\n            };\n            return {\n              queryDescription,\n              value\n            };\n          });\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now()\n            }\n          };\n          return result;\n        }\n      },\n      queryResultPatched: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey,\n            patches\n          }\n        }: PayloadAction<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n            substate.data = applyPatches(substate.data as any, patches.concat());\n          });\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(queryThunk.pending, (draft, {\n        meta,\n        meta: {\n          arg\n        }\n      }) => {\n        const upserting = isUpsertQuery(arg);\n        writePendingCacheEntry(draft, arg, upserting, meta);\n      }).addCase(queryThunk.fulfilled, (draft, {\n        meta,\n        payload\n      }) => {\n        const upserting = isUpsertQuery(meta.arg);\n        writeFulfilledCacheEntry(draft, meta, payload, upserting);\n      }).addCase(queryThunk.rejected, (draft, {\n        meta: {\n          condition,\n          arg,\n          requestId\n        },\n        error,\n        payload\n      }) => {\n        updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n          if (condition) {\n            // request was aborted due to condition (another query already running)\n          } else {\n            // request failed\n            if (substate.requestId !== requestId) return;\n            substate.status = STATUS_REJECTED;\n            substate.error = (payload ?? error) as any;\n          }\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          queries\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(queries)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, {\n          payload\n        }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload);\n          if (cacheKey in draft) {\n            delete draft[cacheKey];\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(mutationThunk.pending, (draft, {\n        meta,\n        meta: {\n          requestId,\n          arg,\n          startedTimeStamp\n        }\n      }) => {\n        if (!arg.track) return;\n        draft[getMutationCacheKey(meta)] = {\n          requestId,\n          status: STATUS_PENDING,\n          endpointName: arg.endpointName,\n          startedTimeStamp\n        };\n      }).addCase(mutationThunk.fulfilled, (draft, {\n        payload,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_FULFILLED;\n          substate.data = payload;\n          substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n        });\n      }).addCase(mutationThunk.rejected, (draft, {\n        payload,\n        error,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_REJECTED;\n          substate.error = (payload ?? error) as any;\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          mutations\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(mutations)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) &&\n          // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n          key !== entry?.requestId) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  type CalculateProvidedByAction = UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>;\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {}\n  };\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(draft, action: PayloadAction<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>) {\n          for (const {\n            queryCacheKey,\n            providedTags\n          } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey);\n            for (const {\n              type,\n              id\n            } of providedTags) {\n              const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] = providedTags as FullTagDescription<string>[];\n          }\n        },\n        prepare: prepareAutoBatched<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n        payload: {\n          queryCacheKey\n        }\n      }) => {\n        removeCacheKeyFromTags(draft, queryCacheKey);\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          provided\n        } = extractRehydrationInfo(action)!;\n        for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {\n          for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n            const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n            for (const queryCacheKey of cacheKeys) {\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n              draft.keys[queryCacheKey] = provided.keys[queryCacheKey];\n            }\n          }\n        }\n      }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n        writeProvidedTagsForQueries(draft, [action]);\n      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {\n        const mockActions: CalculateProvidedByAction[] = action.payload.map(({\n          queryDescription,\n          value\n        }) => {\n          return {\n            type: 'UNKNOWN',\n            payload: value,\n            meta: {\n              requestStatus: 'fulfilled',\n              requestId: 'UNKNOWN',\n              arg: queryDescription\n            }\n          };\n        });\n        writeProvidedTagsForQueries(draft, mockActions);\n      });\n    }\n  });\n  function removeCacheKeyFromTags(draft: InvalidationState<any>, queryCacheKey: QueryCacheKey) {\n    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type;\n      const tagId = tag.id ?? '__internal_without_id';\n      const tagSubscriptions = draft.tags[tagType]?.[tagId];\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(qc => qc !== queryCacheKey);\n      }\n    }\n    delete draft.keys[queryCacheKey];\n  }\n  function writeProvidedTagsForQueries(draft: InvalidationState<string>, actions: CalculateProvidedByAction[]) {\n    const providedByEntries = actions.map(action => {\n      const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n      const {\n        queryCacheKey\n      } = action.meta.arg;\n      return {\n        queryCacheKey,\n        providedTags\n      };\n    });\n    invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(d, a: PayloadAction<{\n        endpointName: string;\n        requestId: string;\n        options: Subscribers[number];\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      unsubscribeQueryResult(d, a: PayloadAction<{\n        requestId: string;\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {}\n    }\n  });\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload);\n        },\n        prepare: prepareAutoBatched<Patch[]>()\n      }\n    }\n  });\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, {\n        payload\n      }: PayloadAction<string>) {\n        state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n      }\n    },\n    extraReducers: builder => {\n      builder.addCase(onOnline, state => {\n        state.online = true;\n      }).addCase(onOffline, state => {\n        state.online = false;\n      }).addCase(onFocus, state => {\n        state.focused = true;\n      }).addCase(onFocusLost, state => {\n        state.focused = false;\n      })\n      // update the state to be a new object to be picked up as a \"state change\"\n      // by redux-persist's `autoMergeLevel2`\n      .addMatcher(hasRehydrationInfo, draft => ({\n        ...draft\n      }));\n    }\n  });\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer\n  });\n  const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState\n  };\n  return {\n    reducer,\n    actions\n  };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { filterMap, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState, QueryStatus } from './apiState';\nimport { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { type AllQueryKeys, getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n  isFetchNextPageError: boolean;\n  isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n  requestId: string | undefined;\n  fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n  status: STATUS_UNINITIALIZED\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  reducerPath: ReducerPath;\n  createSelector: typeof _createSelector;\n}) {\n  type RootState = _RootState<Definitions, string, string>;\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig\n  };\n  function withRequestFlags<T extends {\n    status: QueryStatus;\n  }>(substate: T): T & RequestStatusFlags {\n    return {\n      ...substate,\n      ...getRequestStatusFlags(substate.status)\n    };\n  }\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath];\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state;\n        (selectApiState as any).triggered = true;\n        console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n      }\n    }\n    return state;\n  }\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries;\n  }\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey];\n  }\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations;\n  }\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config;\n  }\n  function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n    status: QueryStatus;\n  }>(substate: T) => T & RequestStatusFlags) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner);\n      }\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n      return createSelector(selectQuerySubstate, combiner);\n    };\n  }\n  function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n  }\n  function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const {\n      infiniteQueryOptions\n    } = endpointDefinition;\n    function withInfiniteQueryResultFlags<T extends {\n      status: QueryStatus;\n    }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status)\n      };\n      const {\n        isLoading,\n        isError,\n        direction\n      } = stateWithRequestFlags;\n      const isForward = direction === 'forward';\n      const isBackward = direction === 'backward';\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward\n      };\n    }\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n  }\n  function buildMutationSelector() {\n    return (id => {\n      let mutationId: string | typeof skipToken;\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken;\n      } else {\n        mutationId = id;\n      }\n      const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n      return createSelector(finalSelectMutationSubstate, withRequestFlags);\n    }) as MutationResultSelectorFactory<any, RootState>;\n  }\n  function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n    endpointName: string;\n    originalArgs: any;\n    queryCacheKey: QueryCacheKey;\n  }> {\n    const apiState = state[reducerPath];\n    const toInvalidate = new Set<QueryCacheKey>();\n    const finalTags = filterMap(tags, isNotNullish, expandTagDescription);\n    for (const tag of finalTags) {\n      const provided = apiState.provided.tags[tag.type];\n      if (!provided) {\n        continue;\n      }\n      let invalidateSubscriptions = (tag.id !== undefined ?\n      // id given: invalidate all queries that provide this type & id\n      provided[tag.id] :\n      // no id: invalidate all queries that provide this type\n      Object.values(provided).flat()) ?? [];\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate);\n      }\n    }\n    return Array.from(toInvalidate.values()).flatMap(queryCacheKey => {\n      const querySubState = apiState.queries[queryCacheKey];\n      return querySubState ? {\n        queryCacheKey,\n        endpointName: querySubState.endpointName!,\n        originalArgs: querySubState.originalArgs\n      } : [];\n    });\n  }\n  function selectCachedArgsForQuery<QueryName extends AllQueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return filterMap(Object.values(selectQueries(state) as QueryState<any>), (entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n      status: QueryStatus.uninitialized;\n    }> => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, entry => entry.originalArgs);\n  }\n  function getHasNextPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data) return false;\n    return getNextPageParam(options, data, queryArg) != null;\n  }\n  function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data || !options.getPreviousPageParam) return false;\n    return getPreviousPageParam(options, data, queryArg) != null;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport { getEndpointDefinition, type Api, type ApiContext, type Module, type ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions, SchemaFailureConverter, SchemaFailureHandler, SchemaType } from './endpointDefinitions';\nimport { DefinitionType, ENDPOINT_INFINITEQUERY, ENDPOINT_MUTATION, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n  /**\n   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery;\n  /**\n   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[];\n  /**\n   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath;\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>;\n  /**\n   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n   */\n  endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n  /**\n   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts'\n   *     })\n   *   }),\n   *   // highlight-start\n   *   keepUnusedDataFor: 5\n   *   // highlight-end\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately';\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (action: UnknownAction, {\n    reducerPath\n  }: {\n    reducerPath: ReducerPath;\n  }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n      reducerPath: (options.reducerPath ?? 'api') as any\n    }));\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n          finalSerializeQueryArgs = queryArgsApi => {\n            const initialResult = endpointSQA(queryArgsApi);\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult;\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult\n              });\n            }\n          };\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs;\n        }\n        return finalSerializeQueryArgs(queryArgsApi);\n      },\n      tagTypes: [...(options.tagTypes || [])]\n    };\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn();\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n    };\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({\n        addTagTypes,\n        endpoints\n      }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;\n              (optionsWithDefaults.tagTypes as any[]).push(eT);\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(getEndpointDefinition(context, endpointName));\n            } else {\n              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);\n            }\n          }\n        }\n        return api;\n      }\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n    const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n    function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: x => ({\n          ...x,\n          type: ENDPOINT_QUERY\n        }) as any,\n        mutation: x => ({\n          ...x,\n          type: ENDPOINT_MUTATION\n        }) as any,\n        infiniteQuery: x => ({\n          ...x,\n          type: ENDPOINT_INFINITEQUERY\n        }) as any\n      });\n      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n            console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          }\n          continue;\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          if (isInfiniteQueryDefinition(definition)) {\n            const {\n              infiniteQueryOptions\n            } = definition;\n            const {\n              maxPages,\n              getPreviousPageParam\n            } = infiniteQueryOptions;\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n              }\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n              }\n            }\n          }\n        }\n        context.endpointDefinitions[endpointName] = definition;\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition);\n        }\n      }\n      return api as any;\n    }\n    return api.injectEndpoints({\n      endpoints: options.endpoints as any\n    });\n  };\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs\n}) => {\n  let serialized = '';\n  const cached = cache?.get(queryArgs);\n  if (typeof cached === 'string') {\n    serialized = cached;\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? {\n        $bigint: value.toString()\n      } : value;\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n        acc[key] = (value as any)[key];\n        return acc;\n      }, {}) : value;\n      return value;\n    });\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified);\n    }\n    serialized = stringified;\n  }\n  return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n  return function () {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n  };\n}","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionInternalState, SubscriptionState } from '../apiState';\nimport { produceWithPatches } from '../../utils/immerImports';\nimport type { Action } from '@reduxjs/toolkit';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n  api,\n  queryThunk,\n  internalState,\n  mwApi\n}) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n  let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n  const {\n    updateSubscriptionOptions,\n    unsubscribeQueryResult\n  } = api.internalActions;\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (currentSubscriptions: SubscriptionInternalState, action: Action) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const {\n        queryCacheKey,\n        requestId,\n        options\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub?.has(requestId)) {\n        sub.set(requestId, options);\n      }\n      return true;\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const {\n        queryCacheKey,\n        requestId\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub) {\n        sub.delete(requestId);\n      }\n      return true;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      currentSubscriptions.delete(action.payload.queryCacheKey);\n      return true;\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: {\n          arg,\n          requestId\n        }\n      } = action;\n      const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n      if (arg.subscribe) {\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n      }\n      return true;\n    }\n    let mutated = false;\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: {\n          condition,\n          arg,\n          requestId\n        }\n      } = action;\n      if (condition && arg.subscribe) {\n        const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n        mutated = true;\n      }\n    }\n    return mutated;\n  };\n  const getSubscriptions = () => internalState.currentSubscriptions;\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions();\n    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);\n    return subscriptionsForQueryArg?.size ?? 0;\n  };\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions();\n    return !!subscriptions?.get(queryCacheKey)?.get(requestId);\n  };\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed\n  };\n  function serializeSubscriptions(currentSubscriptions: SubscriptionInternalState): SubscriptionState {\n    // We now use nested Maps for subscriptions, instead of\n    // plain Records. Stringify this accordingly so we can\n    // convert it to the shape we need for the store.\n    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));\n  }\n  return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);\n    }\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = {};\n      internalState.currentSubscriptions.clear();\n      updateSyncTimer = null;\n      return [true, false];\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors];\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n    let actionShouldContinue = true;\n\n    // HACK Sneak the test-only polling state back out\n    if (process.env.NODE_ENV === 'test' && typeof action.type === 'string' && action.type === `${api.reducerPath}/getPolling`) {\n      return [false, internalState.currentPolls] as any;\n    }\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = serializeSubscriptions(internalState.currentSubscriptions);\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions;\n          updateSyncTimer = null;\n        }, 500);\n      }\n      const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n    }\n    return [actionShouldContinue, false];\n  };\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\n\n/**\n * @example\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => 'posts',\n *       // highlight-start\n *       keepUnusedDataFor: 5\n *       // highlight-end\n *     })\n *   })\n * })\n * ```\n */\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   */\n  keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectConfig\n  },\n  getRunningQueryThunk,\n  mwApi\n}) => {\n  const {\n    removeQueryResult,\n    unsubscribeQueryResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);\n    if (!subscriptions) {\n      return false;\n    }\n    const hasSubscriptions = subscriptions.size > 0;\n    return hasSubscriptions;\n  }\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n  function abortAllPromises<T extends {\n    abort?: () => void;\n  }>(promiseMap: Map<string, T | undefined>): void {\n    for (const promise of promiseMap.values()) {\n      promise?.abort?.();\n    }\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    const state = mwApi.getState();\n    const config = selectConfig(state);\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[];\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n      } else {\n        const {\n          queryCacheKey\n        } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n        queryCacheKeys = [queryCacheKey];\n      }\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n    }\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout);\n        delete currentRemovalTimeouts[key];\n      }\n      abortAllPromises(internalState.runningQueries);\n      abortAllPromises(internalState.runningMutations);\n    }\n    if (context.hasRehydrationInfo(action)) {\n      const {\n        queries\n      } = context.extractRehydrationInfo(action)!;\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n    }\n  };\n  function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n    const state = api.getState();\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey);\n      if (entry?.endpointName) {\n        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config);\n      }\n    }\n  }\n  function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string, api: SubMiddlewareApi, config: ConfigState<string>) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName) as QueryDefinition<any, any, any, any>;\n    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return;\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n      if (currentTimeout) {\n        clearTimeout(currentTimeout);\n      }\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          // Try to abort any running query for this cache key\n          const entry = selectQueryEntry(api.getState(), queryCacheKey);\n          if (entry?.endpointName) {\n            const runningQuery = api.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));\n            runningQuery?.abort();\n          }\n          api.dispatch(removeQueryResult({\n            queryCacheKey\n          }));\n        }\n        delete currentRemovalTimeouts![queryCacheKey];\n      }, finalKeepUnusedDataFor * 1000);\n    }\n  }\n  return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta, BaseQueryResult } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition, DefinitionType } from '../../endpointDefinitions';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nimport { getEndpointDefinition } from '@internal/query/apiTypes';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<{\n    type: DefinitionType.query;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<{\n    type: DefinitionType.mutation;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>;\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>;\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown;\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: MetaType;\n  }, typeof neverResolvedError>;\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectApiState\n  }\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk);\n  const isMutationThunk = isAsyncThunkAction(mutationThunk);\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    valueResolved?(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    cacheEntryRemoved(): void;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const {\n    removeQueryResult,\n    removeMutationResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta\n      });\n      delete lifecycle.valueResolved;\n    }\n  }\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey];\n      lifecycle.cacheEntryRemoved();\n    }\n  }\n  function getActionMetaFields(action: ReturnType<typeof queryThunk.pending> | ReturnType<typeof mutationThunk.pending>) {\n    const {\n      arg,\n      requestId\n    } = action.meta;\n    const {\n      endpointName,\n      originalArgs\n    } = arg;\n    return [endpointName, originalArgs, requestId] as const;\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey;\n    function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    }\n    if (queryThunk.pending.match(action)) {\n      const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);\n    } else if (cacheEntriesUpserted.match(action)) {\n      for (const {\n        queryDescription,\n        value\n      } of action.payload) {\n        const {\n          endpointName,\n          originalArgs,\n          queryCacheKey\n        } = queryDescription;\n        checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n        resolveLifecycleEntry(queryCacheKey, value, {});\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n      if (state) {\n        const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n    } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {\n      removeLifecycleEntry(cacheKey);\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey);\n      }\n    }\n  };\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n    }\n    if (removeQueryResult.match(action)) return action.payload.queryCacheKey;\n    if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n    return '';\n  }\n  function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName);\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n    if (!onCacheEntryAdded) return;\n    const lifecycle = {} as CacheLifecycle;\n    const cacheEntryRemoved = new Promise<void>(resolve => {\n      lifecycle.cacheEntryRemoved = resolve;\n    });\n    const cacheDataLoaded: PromiseWithKnownReason<{\n      data: unknown;\n      meta: unknown;\n    }, typeof neverResolvedError> = Promise.race([new Promise<{\n      data: unknown;\n      meta: unknown;\n    }>(resolve => {\n      lifecycle.valueResolved = resolve;\n    }), cacheEntryRemoved.then(() => {\n      throw neverResolvedError;\n    })]);\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {});\n    lifecycleMap[queryCacheKey] = lifecycle;\n    const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);\n    const extra = mwApi.dispatch((_, __, extra) => extra);\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n      cacheDataLoaded,\n      cacheEntryRemoved\n    };\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch(e => {\n      if (e === neverResolvedError) return;\n      throw e;\n    });\n  }\n  return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: {\n    apiUid\n  },\n  reducerPath\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n      }\n    }\n  };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler } from './types';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: {\n    endpointDefinitions\n  },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));\n  let pendingTagInvalidations: FullTagDescription<string>[] = [];\n  // Track via counter so we can avoid iterating over state every time\n  let pendingRequestCount = 0;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {\n      pendingRequestCount++;\n    }\n    if (isQueryEnd(action)) {\n      pendingRequestCount = Math.max(0, pendingRequestCount - 1);\n    }\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi);\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n    }\n  };\n  function hasPendingRequests() {\n    return pendingRequestCount > 0;\n  }\n  function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n    const rootState = mwApi.getState();\n    const state = rootState[reducerPath];\n    pendingTagInvalidations.push(...newTags);\n    if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests()) {\n      return;\n    }\n    const tags = pendingTagInvalidations;\n    pendingTagInvalidations = [];\n    if (tags.length === 0) return;\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values());\n      for (const {\n        queryCacheKey\n      } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey];\n        const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);\n        if (querySubState) {\n          if (subscriptionSubState.size === 0) {\n            mwApi.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            mwApi.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers, SubscribersInternal } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    currentPolls,\n    currentSubscriptions\n  } = internalState;\n\n  // Batching state for polling updates\n  const pendingPollingUpdates = new Set<string>();\n  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n      schedulePollingUpdate(action.payload.queryCacheKey, mwApi);\n    }\n    if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);\n    }\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n      startNextPoll(action.meta.arg, mwApi);\n    }\n    if (api.util.resetApiState.match(action)) {\n      clearPolls();\n      // Clear any pending updates\n      if (pollingUpdateTimer) {\n        clearTimeout(pollingUpdateTimer);\n        pollingUpdateTimer = null;\n      }\n      pendingPollingUpdates.clear();\n    }\n  };\n  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {\n    pendingPollingUpdates.add(queryCacheKey);\n    if (!pollingUpdateTimer) {\n      pollingUpdateTimer = setTimeout(() => {\n        // Process all pending updates in a single batch\n        for (const key of pendingPollingUpdates) {\n          updatePollingInterval({\n            queryCacheKey: key as any\n          }, api);\n        }\n        pendingPollingUpdates.clear();\n        pollingUpdateTimer = null;\n      }, 0);\n    }\n  }\n  function startNextPoll({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;\n    const {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) return;\n    const currentPoll = currentPolls.get(queryCacheKey);\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout);\n      currentPoll.timeout = undefined;\n    }\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    currentPolls.set(queryCacheKey, {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState));\n        }\n        startNextPoll({\n          queryCacheKey\n        }, api);\n      }, lowestPollingInterval)\n    });\n  }\n  function updatePollingInterval({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {\n      return;\n    }\n    const {\n      lowestPollingInterval\n    } = findLowestPollingInterval(subscriptions);\n\n    // HACK add extra data to track how many times this has been called in tests\n    // yes we're mutating a nonexistent field on a Map here\n    if (process.env.NODE_ENV === 'test') {\n      const updateCounters = (currentPolls as any).pollUpdateCounters ??= {};\n      updateCounters[queryCacheKey] ??= 0;\n      updateCounters[queryCacheKey]++;\n    }\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey);\n      return;\n    }\n    const currentPoll = currentPolls.get(queryCacheKey);\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({\n        queryCacheKey\n      }, api);\n    }\n  }\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls.get(key);\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout);\n    }\n    currentPolls.delete(key);\n  }\n  function clearPolls() {\n    for (const key of currentPolls.keys()) {\n      cleanupPollForKey(key);\n    }\n  }\n  function findLowestPollingInterval(subscribers: SubscribersInternal = new Map()) {\n    let skipPollingIfUnfocused: boolean | undefined = false;\n    let lowestPollingInterval = Number.POSITIVE_INFINITY;\n    for (const entry of subscribers.values()) {\n      if (!!entry.pollingInterval) {\n        lowestPollingInterval = Math.min(entry.pollingInterval!, lowestPollingInterval);\n        skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;\n      }\n    }\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    };\n  }\n  return handler;\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: BaseQueryMeta<BaseQuery>;\n  }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n  error: BaseQueryError<BaseQuery>;\n  /**\n   * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n   */\n  isUnhandledError: false;\n  /**\n   * The `meta` returned by the `baseQuery`\n   */\n  meta: BaseQueryMeta<BaseQuery>;\n} | {\n  error: unknown;\n  meta?: undefined;\n  /**\n   * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n   * There can not be made any assumption about the shape of `error`.\n   */\n  isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * import { messageCreated } from './notificationsSlice\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'))\n   *         try {\n   *           const { data } = await queryFulfilled\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'))\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'))\n   *         }\n   *       }\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk);\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    resolve(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    reject(value: QueryFulfilledRejectionReason<any>): unknown;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: {\n          endpointName,\n          originalArgs\n        }\n      } = action.meta;\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const onQueryStarted = endpointDefinition?.onQueryStarted;\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle;\n        const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n          data: unknown;\n          meta: unknown;\n        }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n          lifecycle.resolve = resolve;\n          lifecycle.reject = reject;\n        });\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {});\n        lifecycleMap[requestId] = lifecycle;\n        const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);\n        const extra = mwApi.dispatch((_, __, extra) => extra);\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n          queryFulfilled\n        };\n        onQueryStarted(originalArgs, lifecycleApi as any);\n      }\n    } else if (isFullfilledThunk(action)) {\n      const {\n        requestId,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta\n      });\n      delete lifecycleMap[requestId];\n    } else if (isRejectedThunk(action)) {\n      const {\n        requestId,\n        rejectedWithValue,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any\n      });\n      delete lifecycleMap[requestId];\n    }\n  };\n  return handler;\n};","import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus');\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect');\n    }\n  };\n  function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n    const state = api.getState()[reducerPath];\n    const queries = state.queries;\n    const subscriptions = internalState.currentSubscriptions;\n    context.batch(() => {\n      for (const queryCacheKey of subscriptions.keys()) {\n        const querySubState = queries[queryCacheKey];\n        const subscriptionSubState = subscriptions.get(queryCacheKey);\n        if (!subscriptionSubState || !querySubState) continue;\n        const values = [...subscriptionSubState.values()];\n        const shouldRefetch = values.some(sub => sub[type] === true) || values.every(sub => sub[type] === undefined) && state.config[type];\n        if (shouldRefetch) {\n          if (subscriptionSubState.size === 0) {\n            api.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            api.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const {\n    reducerPath,\n    queryThunk,\n    api,\n    context,\n    getInternalState\n  } = input;\n  const {\n    apiUid\n  } = context;\n  const actions = {\n    invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n  };\n  const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n  const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n  const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n    let initialized = false;\n    const internalState = getInternalState(mwApi.dispatch);\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction,\n      mwApi\n    };\n    const handlers = handlerBuilders.map(build => build(builderArgs));\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n    const windowEventsHandler = buildWindowEventHandler(builderArgs);\n    return next => {\n      return action => {\n        if (!isAction(action)) {\n          return next(action);\n        }\n        if (!initialized) {\n          initialized = true;\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n        }\n        const mwApiWithNext = {\n          ...mwApi,\n          next\n        };\n        const stateBefore = mwApi.getState();\n        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n        let res: any;\n        if (actionShouldContinue) {\n          res = next(action);\n        } else {\n          res = internalProbeResult;\n        }\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore);\n          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore);\n            }\n          }\n        }\n        return res;\n      };\n    };\n  };\n  return {\n    middleware,\n    actions\n  };\n  function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n    status: QueryStatus.uninitialized;\n  }>) {\n    return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true\n    });\n  }\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Dispatch, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from '../utils/immerImports';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nimport { getOrInsertComputed } from '../utils';\nimport type { CreateSelectorFunction } from 'reselect';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n */\nexport type PrefetchOptions = {\n  ifOlderThan?: false | number;\n} | {\n  force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath;\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions;\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n    /**\n     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'query';\n      }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'infinitequery';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n        type: 'mutation';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n       *\n       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n      /**\n       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n       *\n       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n       *\n       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n       *\n       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n       *\n       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n      /**\n       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n       *\n       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n       *\n       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState'];\n      upsertQueryEntries: UpsertEntries<Definitions>;\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n       *\n       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n       *\n       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n        endpointName: string;\n        originalArgs: any;\n        queryCacheKey: string;\n      }>;\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;\n    };\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never };\n  };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(api, {\n    baseQuery,\n    tagTypes,\n    reducerPath,\n    serializeQueryArgs,\n    keepUnusedDataFor,\n    refetchOnMountOrArgChange,\n    refetchOnFocus,\n    refetchOnReconnect,\n    invalidationBehavior,\n    onSchemaFailure,\n    catchSchemaFailure,\n    skipSchemaValidation\n  }, context) {\n    enablePatches();\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n    const assertTagType: AssertTagTypes = tag => {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n        }\n      }\n      return tag;\n    };\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost\n      },\n      util: {}\n    });\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector\n    });\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector\n    } = selectors;\n    safeAssign(api.util, {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery\n    });\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation\n    });\n    const {\n      reducer,\n      actions: sliceActions\n    } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior\n      }\n    });\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n    });\n    safeAssign(api.internalActions, sliceActions);\n    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>();\n    const getInternalState = (dispatch: Dispatch) => {\n      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({\n        currentSubscriptions: new Map(),\n        currentPolls: new Map(),\n        runningQueries: new Map(),\n        runningMutations: new Map()\n      }));\n      return state;\n    };\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context,\n      getInternalState\n    });\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk\n    });\n    const {\n      middleware,\n      actions: middlewareActions\n    } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors,\n      getRunningQueryThunk,\n      getInternalState\n    });\n    safeAssign(api.util, middlewareActions);\n    safeAssign(api, {\n      reducer: reducer as any,\n      middleware\n    });\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n        const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n        if (isQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildQuerySelector(endpointName, definition),\n            initiate: buildInitiateQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildMutationSelector(),\n            initiate: buildInitiateMutation(endpointName)\n          }, buildMatchThunkActions(mutationThunk, endpointName));\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildInfiniteQuerySelector(endpointName, definition),\n            initiate: buildInitiateInfiniteQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n      }\n    };\n  }\n});","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,mBAAgB;AAChB,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,cAAW;AAJD,SAAAA;AAAA,GAAA;AAQL,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AA0BxB,SAAS,sBAAsB,QAAyC;AAC7E,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,WAAW;AAAA,IAC5B,WAAW,WAAW;AAAA,IACtB,WAAW,WAAW;AAAA,IACtB,SAAS,WAAW;AAAA,EACtB;AACF;;;AC3GA,SAAS,cAAc,aAAa,gBAAgB,kBAAkB,iBAAiB,iBAAiB,SAAS,SAAS,UAAU,WAAW,YAAY,aAAa,qBAAqB,oBAAoB,oBAAoB,kBAAkB,eAAe,cAAc;;;ACDpR,IAAMC,iBAAqC;AAEpC,SAAS,0BAA0B,QAAa,QAAkB;AACvE,MAAI,WAAW,UAAU,EAAEA,eAAc,MAAM,KAAKA,eAAc,MAAM,KAAK,MAAM,QAAQ,MAAM,KAAK,MAAM,QAAQ,MAAM,IAA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;AAAA,YACnD,UAAU,mBAAmB,cAAc,UAAU;AAAA,UACvD,GAAG,uBAAuB,YAAY,YAAY,CAAC;AAAA,QACrD;AACA,YAAI,qBAAqB,UAAU,GAAG;AACpC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,sBAAsB;AAAA,YAC9B,UAAU,sBAAsB,YAAY;AAAA,UAC9C,GAAG,uBAAuB,eAAe,YAAY,CAAC;AAAA,QACxD;AACA,YAAI,0BAA0B,UAAU,GAAG;AACzC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,2BAA2B,cAAc,UAAU;AAAA,YAC3D,UAAU,2BAA2B,cAAc,UAAU;AAAA,UAC/D,GAAG,uBAAuB,YAAY,YAAY,CAAC;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACniBO,IAAM,YAA2B,+BAAe,WAAW,CAAC;","names":["QueryStatus","isPlainObject","_a","retry","updateListeners","_a","arg","force","options","actions","createSelector","_a","_formatProdErrorMessage","_formatProdErrorMessage2","key","queryArgsApi","_formatProdErrorMessage","getPreviousPageParam","_formatProdErrorMessage2","_formatProdErrorMessage","mwApi","mwApi","api","cacheKey","extra","api","extra","api","actions","initialized","createSelector"]}
Index: node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3047 @@
+// src/query/core/apiState.ts
+var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
+  QueryStatus7["uninitialized"] = "uninitialized";
+  QueryStatus7["pending"] = "pending";
+  QueryStatus7["fulfilled"] = "fulfilled";
+  QueryStatus7["rejected"] = "rejected";
+  return QueryStatus7;
+})(QueryStatus || {});
+var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
+var STATUS_PENDING = "pending" /* pending */;
+var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
+var STATUS_REJECTED = "rejected" /* rejected */;
+function getRequestStatusFlags(status) {
+  return {
+    status,
+    isUninitialized: status === STATUS_UNINITIALIZED,
+    isLoading: status === STATUS_PENDING,
+    isSuccess: status === STATUS_FULFILLED,
+    isError: status === STATUS_REJECTED
+  };
+}
+
+// src/query/core/rtkImports.ts
+import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
+
+// src/query/utils/copyWithStructuralSharing.ts
+var isPlainObject2 = isPlainObject;
+function copyWithStructuralSharing(oldObj, newObj) {
+  if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
+    return newObj;
+  }
+  const newKeys = Object.keys(newObj);
+  const oldKeys = Object.keys(oldObj);
+  let isSameObject = newKeys.length === oldKeys.length;
+  const mergeObj = Array.isArray(newObj) ? [] : {};
+  for (const key of newKeys) {
+    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
+    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
+  }
+  return isSameObject ? oldObj : mergeObj;
+}
+
+// src/query/utils/filterMap.ts
+function filterMap(array, predicate, mapper) {
+  return array.reduce((acc, item, i) => {
+    if (predicate(item, i)) {
+      acc.push(mapper(item, i));
+    }
+    return acc;
+  }, []).flat();
+}
+
+// src/query/utils/isAbsoluteUrl.ts
+function isAbsoluteUrl(url) {
+  return new RegExp(`(^|:)//`).test(url);
+}
+
+// src/query/utils/isDocumentVisible.ts
+function isDocumentVisible() {
+  if (typeof document === "undefined") {
+    return true;
+  }
+  return document.visibilityState !== "hidden";
+}
+
+// src/query/utils/isNotNullish.ts
+function isNotNullish(v) {
+  return v != null;
+}
+function filterNullishValues(map) {
+  return [...map?.values() ?? []].filter(isNotNullish);
+}
+
+// src/query/utils/isOnline.ts
+function isOnline() {
+  return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
+}
+
+// src/query/utils/joinUrls.ts
+var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
+var withoutLeadingSlash = (url) => url.replace(/^\//, "");
+function joinUrls(base, url) {
+  if (!base) {
+    return url;
+  }
+  if (!url) {
+    return base;
+  }
+  if (isAbsoluteUrl(url)) {
+    return url;
+  }
+  const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
+  base = withoutTrailingSlash(base);
+  url = withoutLeadingSlash(url);
+  return `${base}${delimiter}${url}`;
+}
+
+// src/query/utils/getOrInsert.ts
+function getOrInsertComputed(map, key, compute) {
+  if (map.has(key)) return map.get(key);
+  return map.set(key, compute(key)).get(key);
+}
+var createNewMap = () => /* @__PURE__ */ new Map();
+
+// src/query/utils/signals.ts
+var timeoutSignal = (milliseconds) => {
+  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;
+};
+var anySignal = (...signals) => {
+  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
+  const abortController = new AbortController();
+  for (const signal of signals) {
+    signal.addEventListener("abort", () => abortController.abort(signal.reason), {
+      signal: abortController.signal,
+      once: true
+    });
+  }
+  return abortController.signal;
+};
+
+// src/query/fetchBaseQuery.ts
+var defaultFetchFn = (...args) => fetch(...args);
+var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
+var defaultIsJsonContentType = (headers) => (
+  /*applicat*/
+  /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
+);
+function stripUndefined(obj) {
+  if (!isPlainObject(obj)) {
+    return obj;
+  }
+  const copy = {
+    ...obj
+  };
+  for (const [k, v] of Object.entries(copy)) {
+    if (v === void 0) delete copy[k];
+  }
+  return copy;
+}
+var isJsonifiable = (body) => typeof body === "object" && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === "function");
+function fetchBaseQuery({
+  baseUrl,
+  prepareHeaders = (x) => x,
+  fetchFn = defaultFetchFn,
+  paramsSerializer,
+  isJsonContentType = defaultIsJsonContentType,
+  jsonContentType = "application/json",
+  jsonReplacer,
+  timeout: defaultTimeout,
+  responseHandler: globalResponseHandler,
+  validateStatus: globalValidateStatus,
+  ...baseFetchOptions
+} = {}) {
+  if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
+    console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
+  }
+  return async (arg, api, extraOptions) => {
+    const {
+      getState,
+      extra,
+      endpoint,
+      forced,
+      type
+    } = api;
+    let meta;
+    let {
+      url,
+      headers = new Headers(baseFetchOptions.headers),
+      params = void 0,
+      responseHandler = globalResponseHandler ?? "json",
+      validateStatus = globalValidateStatus ?? defaultValidateStatus,
+      timeout = defaultTimeout,
+      ...rest
+    } = typeof arg == "string" ? {
+      url: arg
+    } : arg;
+    let config = {
+      ...baseFetchOptions,
+      signal: 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);
+    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);
+    }
+    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, */*");
+      }
+    }
+    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;
+    let responseText = "";
+    try {
+      let handleResponseError;
+      await Promise.all([
+        handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
+        // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
+        // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
+        responseClone.text().then((r) => responseText = r, () => {
+        })
+      ]);
+      if (handleResponseError) throw handleResponseError;
+    } catch (e) {
+      return {
+        error: {
+          status: "PARSING_ERROR",
+          originalStatus: response.status,
+          data: responseText,
+          error: String(e)
+        },
+        meta
+      };
+    }
+    return validateStatus(response, resultData) ? {
+      data: resultData,
+      meta
+    } : {
+      error: {
+        status: response.status,
+        data: resultData
+      },
+      meta
+    };
+  };
+  async function handleResponse(response, responseHandler) {
+    if (typeof responseHandler === "function") {
+      return responseHandler(response);
+    }
+    if (responseHandler === "content-type") {
+      responseHandler = isJsonContentType(response.headers) ? "json" : "text";
+    }
+    if (responseHandler === "json") {
+      const text = await response.text();
+      return text.length ? JSON.parse(text) : null;
+    }
+    return response.text();
+  }
+}
+
+// src/query/HandledError.ts
+var HandledError = class {
+  constructor(value, meta = void 0) {
+    this.value = value;
+    this.meta = meta;
+  }
+};
+
+// src/query/retry.ts
+async function defaultBackoff(attempt = 0, maxRetries = 5, signal) {
+  const attempts = Math.min(attempt, maxRetries);
+  const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
+  await new Promise((resolve, reject) => {
+    const timeoutId = setTimeout(() => resolve(), timeout);
+    if (signal) {
+      const abortHandler = () => {
+        clearTimeout(timeoutId);
+        reject(new Error("Aborted"));
+      };
+      if (signal.aborted) {
+        clearTimeout(timeoutId);
+        reject(new Error("Aborted"));
+      } else {
+        signal.addEventListener("abort", abortHandler, {
+          once: true
+        });
+      }
+    }
+  });
+}
+function fail(error, meta) {
+  throw Object.assign(new HandledError({
+    error,
+    meta
+  }), {
+    throwImmediately: true
+  });
+}
+function failIfAborted(signal) {
+  if (signal.aborted) {
+    fail({
+      status: "CUSTOM_ERROR",
+      error: "Aborted"
+    });
+  }
+}
+var EMPTY_OPTIONS = {};
+var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
+  const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
+  const [maxRetries] = possibleMaxRetries.slice(-1);
+  const defaultRetryCondition = (_, __, {
+    attempt
+  }) => attempt <= maxRetries;
+  const options = {
+    maxRetries,
+    backoff: defaultBackoff,
+    retryCondition: defaultRetryCondition,
+    ...defaultOptions,
+    ...extraOptions
+  };
+  let retry2 = 0;
+  while (true) {
+    failIfAborted(api.signal);
+    try {
+      const result = await baseQuery(args, api, extraOptions);
+      if (result.error) {
+        throw new HandledError(result);
+      }
+      return result;
+    } catch (e) {
+      retry2++;
+      if (e.throwImmediately) {
+        if (e instanceof HandledError) {
+          return e.value;
+        }
+        throw e;
+      }
+      if (e instanceof HandledError) {
+        if (!options.retryCondition(e.value.error, args, {
+          attempt: retry2,
+          baseQueryApi: api,
+          extraOptions
+        })) {
+          return e.value;
+        }
+      } else {
+        if (retry2 > options.maxRetries) {
+          return {
+            error: e
+          };
+        }
+      }
+      failIfAborted(api.signal);
+      try {
+        await options.backoff(retry2, options.maxRetries, api.signal);
+      } catch (backoffError) {
+        failIfAborted(api.signal);
+        throw backoffError;
+      }
+    }
+  }
+};
+var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
+  fail
+});
+
+// src/query/core/setupListeners.ts
+var INTERNAL_PREFIX = "__rtkq/";
+var ONLINE = "online";
+var OFFLINE = "offline";
+var FOCUS = "focus";
+var FOCUSED = "focused";
+var VISIBILITYCHANGE = "visibilitychange";
+var onFocus = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${FOCUSED}`);
+var onFocusLost = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);
+var onOnline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${ONLINE}`);
+var onOffline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${OFFLINE}`);
+var actions = {
+  onFocus,
+  onFocusLost,
+  onOnline,
+  onOffline
+};
+var initialized = false;
+function setupListeners(dispatch, customHandler) {
+  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) {
+        let updateListeners2 = function(add) {
+          Object.entries(handlers).forEach(([event, handler]) => {
+            if (add) {
+              window.addEventListener(event, handler, false);
+            } else {
+              window.removeEventListener(event, handler);
+            }
+          });
+        };
+        var updateListeners = updateListeners2;
+        const handlers = {
+          [FOCUS]: handleFocus,
+          [VISIBILITYCHANGE]: handleVisibilityChange,
+          [ONLINE]: handleOnline,
+          [OFFLINE]: handleOffline
+        };
+        updateListeners2(true);
+        initialized = true;
+        unsubscribe = () => {
+          updateListeners2(false);
+          initialized = false;
+        };
+      }
+    }
+    return unsubscribe;
+  }
+  return customHandler ? customHandler(dispatch, actions) : defaultHandler();
+}
+
+// src/query/endpointDefinitions.ts
+var ENDPOINT_QUERY = "query" /* query */;
+var ENDPOINT_MUTATION = "mutation" /* mutation */;
+var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
+function isQueryDefinition(e) {
+  return e.type === ENDPOINT_QUERY;
+}
+function isMutationDefinition(e) {
+  return e.type === ENDPOINT_MUTATION;
+}
+function isInfiniteQueryDefinition(e) {
+  return e.type === ENDPOINT_INFINITEQUERY;
+}
+function isAnyQueryDefinition(e) {
+  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);
+}
+function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
+  const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
+  if (finalDescription) {
+    return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
+  }
+  return [];
+}
+function isFunction(t) {
+  return typeof t === "function";
+}
+function expandTagDescription(description) {
+  return typeof description === "string" ? {
+    type: description
+  } : description;
+}
+
+// src/query/utils/immerImports.ts
+import { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from "immer";
+
+// src/query/core/buildInitiate.ts
+import { formatProdErrorMessage as _formatProdErrorMessage } from "@reduxjs/toolkit";
+
+// src/tsHelpers.ts
+function asSafePromise(promise, fallback) {
+  return promise.catch(fallback);
+}
+
+// src/query/apiTypes.ts
+var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
+
+// src/query/core/buildInitiate.ts
+var forceQueryFnSymbol = Symbol("forceQueryFn");
+var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
+function buildInitiate({
+  serializeQueryArgs,
+  queryThunk,
+  infiniteQueryThunk,
+  mutationThunk,
+  api,
+  context,
+  getInternalState
+}) {
+  const getRunningQueries = (dispatch) => getInternalState(dispatch)?.runningQueries;
+  const getRunningMutations = (dispatch) => getInternalState(dispatch)?.runningMutations;
+  const {
+    unsubscribeQueryResult,
+    removeMutationResult,
+    updateSubscriptionOptions
+  } = api.internalActions;
+  return {
+    buildInitiateQuery,
+    buildInitiateInfiniteQuery,
+    buildInitiateMutation,
+    getRunningQueryThunk,
+    getRunningMutationThunk,
+    getRunningQueriesThunk,
+    getRunningMutationsThunk
+  };
+  function getRunningQueryThunk(endpointName, queryArgs) {
+    return (dispatch) => {
+      const endpointDefinition = getEndpointDefinition(context, endpointName);
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      });
+      return getRunningQueries(dispatch)?.get(queryCacheKey);
+    };
+  }
+  function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
+    return (dispatch) => {
+      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId);
+    };
+  }
+  function getRunningQueriesThunk() {
+    return (dispatch) => filterNullishValues(getRunningQueries(dispatch));
+  }
+  function getRunningMutationsThunk() {
+    return (dispatch) => filterNullishValues(getRunningMutations(dispatch));
+  }
+  function middlewareWarning(dispatch) {
+    if (process.env.NODE_ENV !== "production") {
+      if (middlewareWarning.triggered) return;
+      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
+      middlewareWarning.triggered = true;
+      if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
+        throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+You must add the middleware for RTK-Query to function correctly!`);
+      }
+    }
+  }
+  function buildInitiateAnyQuery(endpointName, endpointDefinition) {
+    const queryAction = (arg, {
+      subscribe = true,
+      forceRefetch,
+      subscriptionOptions,
+      [forceQueryFnSymbol]: forceQueryFn,
+      ...rest
+    } = {}) => (dispatch, getState) => {
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs: arg,
+        endpointDefinition,
+        endpointName
+      });
+      let thunk;
+      const commonThunkArgs = {
+        ...rest,
+        type: ENDPOINT_QUERY,
+        subscribe,
+        forceRefetch,
+        subscriptionOptions,
+        endpointName,
+        originalArgs: arg,
+        queryCacheKey,
+        [forceQueryFnSymbol]: forceQueryFn
+      };
+      if (isQueryDefinition(endpointDefinition)) {
+        thunk = queryThunk(commonThunkArgs);
+      } else {
+        const {
+          direction,
+          initialPageParam,
+          refetchCachedPages
+        } = rest;
+        thunk = infiniteQueryThunk({
+          ...commonThunkArgs,
+          // Supply these even if undefined. This helps with a field existence
+          // check over in `buildSlice.ts`
+          direction,
+          initialPageParam,
+          refetchCachedPages
+        });
+      }
+      const selector = api.endpoints[endpointName].select(arg);
+      const thunkResult = dispatch(thunk);
+      const stateAfter = selector(getState());
+      middlewareWarning(dispatch);
+      const {
+        requestId,
+        abort
+      } = thunkResult;
+      const skippedSynchronously = stateAfter.requestId !== requestId;
+      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);
+      const selectFromState = () => selector(getState());
+      const statePromise = Object.assign(forceQueryFn ? (
+        // a query has been forced (upsertQueryData)
+        // -> we want to resolve it once data has been written with the data that will be written
+        thunkResult.then(selectFromState)
+      ) : skippedSynchronously && !runningQuery ? (
+        // a query has been skipped due to a condition and we do not have any currently running query
+        // -> we want to resolve it immediately with the current data
+        Promise.resolve(stateAfter)
+      ) : (
+        // query just started or one is already in flight
+        // -> wait for the running query, then resolve with data from after that
+        Promise.all([runningQuery, thunkResult]).then(selectFromState)
+      ), {
+        arg,
+        requestId,
+        subscriptionOptions,
+        queryCacheKey,
+        abort,
+        async unwrap() {
+          const result = await statePromise;
+          if (result.isError) {
+            throw result.error;
+          }
+          return result.data;
+        },
+        refetch: (options) => dispatch(queryAction(arg, {
+          subscribe: false,
+          forceRefetch: true,
+          ...options
+        })),
+        unsubscribe() {
+          if (subscribe) dispatch(unsubscribeQueryResult({
+            queryCacheKey,
+            requestId
+          }));
+        },
+        updateSubscriptionOptions(options) {
+          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, endpointDefinition) {
+    const queryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
+    return queryAction;
+  }
+  function buildInitiateInfiniteQuery(endpointName, endpointDefinition) {
+    const infiniteQueryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
+    return infiniteQueryAction;
+  }
+  function buildInitiateMutation(endpointName) {
+    return (arg, {
+      track = true,
+      fixedCacheKey
+    } = {}) => (dispatch, getState) => {
+      const thunk = mutationThunk({
+        type: "mutation",
+        endpointName,
+        originalArgs: arg,
+        track,
+        fixedCacheKey
+      });
+      const thunkResult = dispatch(thunk);
+      middlewareWarning(dispatch);
+      const {
+        requestId,
+        abort,
+        unwrap
+      } = thunkResult;
+      const returnValuePromise = 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;
+    };
+  }
+}
+
+// src/query/standardSchema.ts
+import { SchemaError } from "@standard-schema/utils";
+var NamedSchemaError = class extends SchemaError {
+  constructor(issues, value, schemaName, _bqMeta) {
+    super(issues);
+    this.value = value;
+    this.schemaName = schemaName;
+    this._bqMeta = _bqMeta;
+  }
+};
+var shouldSkip = (skipSchemaValidation, schemaName) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;
+async function parseWithSchema(schema, data, schemaName, bqMeta) {
+  const result = await schema["~standard"].validate(data);
+  if (result.issues) {
+    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);
+  }
+  return result.value;
+}
+
+// src/query/core/buildThunks.ts
+function defaultTransformResponse(baseQueryReturnValue) {
+  return baseQueryReturnValue;
+}
+var addShouldAutoBatch = (arg = {}) => {
+  return {
+    ...arg,
+    [SHOULD_AUTOBATCH]: true
+  };
+};
+function buildThunks({
+  reducerPath,
+  baseQuery,
+  context: {
+    endpointDefinitions
+  },
+  serializeQueryArgs,
+  api,
+  assertTagType,
+  selectors,
+  onSchemaFailure,
+  catchSchemaFailure: globalCatchSchemaFailure,
+  skipSchemaValidation: globalSkipSchemaValidation
+}) {
+  const patchQueryData = (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()
+    );
+    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
+    dispatch(api.internalActions.updateProvidedBy([{
+      queryCacheKey,
+      providedTags
+    }]));
+  };
+  function addToStart(items, item, max = 0) {
+    const newItems = [item, ...items];
+    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
+  }
+  function addToEnd(items, item, max = 0) {
+    const newItems = [...items, item];
+    return max && newItems.length > max ? newItems.slice(1) : newItems;
+  }
+  const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
+    const endpointDefinition = api.endpoints[endpointName];
+    const currentState = endpointDefinition.select(arg)(
+      // Work around TS 4.1 mismatch
+      getState()
+    );
+    const ret = {
+      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 = (endpointName, arg, value) => (dispatch) => {
+    const res = dispatch(api.endpoints[endpointName].initiate(arg, {
+      subscribe: false,
+      forceRefetch: true,
+      [forceQueryFnSymbol]: () => ({
+        data: value
+      })
+    }));
+    return res;
+  };
+  const getTransformCallbackForEndpoint = (endpointDefinition, transformFieldName) => {
+    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName] : defaultTransformResponse;
+  };
+  const executeEndpoint = 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 = defaultTransformResponse;
+      const baseQueryApi = {
+        signal,
+        abort,
+        dispatch,
+        getState,
+        extra,
+        endpoint: arg.endpointName,
+        type: arg.type,
+        forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
+        queryCacheKey: isQuery ? arg.queryCacheKey : void 0
+      };
+      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
+      let finalQueryReturnValue;
+      const fetchPage = async (data, param, maxPages, previous) => {
+        if (param == null && data.pages.length) {
+          return Promise.resolve({
+            data
+          });
+        }
+        const finalQueryArg = {
+          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
+        };
+      };
+      async function executeRequest(finalQueryArg) {
+        let result;
+        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) {
+          result = forceQueryFn();
+        } else if (endpointDefinition.query) {
+          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformResponse");
+          result = await baseQuery(endpointDefinition.query(finalQueryArg), baseQueryApi, extraOptions);
+        } else {
+          result = await endpointDefinition.queryFn(finalQueryArg, baseQueryApi, extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, extraOptions));
+        }
+        if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+          const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
+          let err;
+          if (!result) {
+            err = `${what} did not return anything.`;
+          } else if (typeof result !== "object") {
+            err = `${what} did not return an object.`;
+          } else if (result.error && result.data) {
+            err = `${what} returned an object containing both \`error\` and \`result\`.`;
+          } else if (result.error === void 0 && result.data === void 0) {
+            err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
+          } else {
+            for (const key of Object.keys(result)) {
+              if (key !== "error" && key !== "data" && key !== "meta") {
+                err = `The object returned by ${what} has the unknown property ${key}.`;
+                break;
+              }
+            }
+          }
+          if (err) {
+            console.error(`Error encountered handling the endpoint ${arg.endpointName}.
+                  ${err}
+                  It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
+                  Object returned was:`, result);
+          }
+        }
+        if (result.error) throw new HandledError(result.error, result.meta);
+        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) {
+        const {
+          infiniteQueryOptions
+        } = endpointDefinition;
+        const {
+          maxPages = Infinity
+        } = infiniteQueryOptions;
+        const refetchCachedPages = arg.refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;
+        let result;
+        const blankData = {
+          pages: [],
+          pageParams: []
+        };
+        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data;
+        const isForcedQueryNeedingRefetch = (
+          // arg.forceRefetch
+          isForcedQuery(arg, getState()) && !arg.direction
+        );
+        const existingData = isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData;
+        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 {
+          const {
+            initialPageParam = infiniteQueryOptions.initialPageParam
+          } = arg;
+          const cachedPageParams = cachedData?.pageParams ?? [];
+          const firstPageParam = cachedPageParams[0] ?? initialPageParam;
+          const totalPages = cachedPageParams.length;
+          result = await fetchPage(existingData, firstPageParam, maxPages);
+          if (forceQueryFn) {
+            result = {
+              data: result.data.pages[0]
+            };
+          }
+          if (refetchCachedPages) {
+            for (let i = 1; i < totalPages; i++) {
+              const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
+              result = await fetchPage(result.data, param, maxPages);
+            }
+          }
+        }
+        finalQueryReturnValue = result;
+      } else {
+        finalQueryReturnValue = await executeRequest(arg.originalArgs);
+      }
+      if (metaSchema && !shouldSkip(skipSchemaValidation, "meta") && finalQueryReturnValue.meta) {
+        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, "metaSchema", finalQueryReturnValue.meta);
+      }
+      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 = {
+            endpoint: arg.endpointName,
+            arg: arg.originalArgs,
+            type: arg.type,
+            queryCacheKey: isQuery ? arg.queryCacheKey : void 0
+          };
+          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, state) {
+    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 refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
+    }
+    return false;
+  }
+  const createQueryThunk = () => {
+    const generatedQueryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
+      getPendingMeta({
+        arg
+      }) {
+        const endpointDefinition = endpointDefinitions[arg.endpointName];
+        return addShouldAutoBatch({
+          startedTimeStamp: Date.now(),
+          ...isInfiniteQueryDefinition(endpointDefinition) ? {
+            direction: arg.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.direction;
+        if (isUpsertQuery(queryThunkArg)) {
+          return true;
+        }
+        if (requestState?.status === "pending") {
+          return false;
+        }
+        if (isForcedQuery(queryThunkArg, state)) {
+          return true;
+        }
+        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
+          currentArg,
+          previousArg,
+          endpointState: requestState,
+          state
+        })) {
+          return true;
+        }
+        if (fulfilledVal && !direction) {
+          return false;
+        }
+        return true;
+      },
+      dispatchConditionRejection: true
+    });
+    return generatedQueryThunk;
+  };
+  const queryThunk = createQueryThunk();
+  const infiniteQueryThunk = createQueryThunk();
+  const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
+    getPendingMeta() {
+      return addShouldAutoBatch({
+        startedTimeStamp: Date.now()
+      });
+    }
+  });
+  const hasTheForce = (options) => "force" in options;
+  const hasMaxAge = (options) => "ifOlderThan" in options;
+  const prefetch = (endpointName, arg, options = {}) => (dispatch, getState) => {
+    const force = hasTheForce(options) && options.force;
+    const maxAge = hasMaxAge(options) && options.ifOlderThan;
+    const queryAction = (force2 = true) => {
+      const options2 = {
+        forceRefetch: force2,
+        subscribe: false
+      };
+      return api.endpoints[endpointName].initiate(arg, options2);
+    };
+    const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
+    if (force) {
+      dispatch(queryAction());
+    } else if (maxAge) {
+      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
+      if (!lastFulfilledTs) {
+        dispatch(queryAction());
+        return;
+      }
+      const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
+      if (shouldRetrigger) {
+        dispatch(queryAction());
+      }
+    } else {
+      dispatch(queryAction(false));
+    }
+  };
+  function matchesEndpoint(endpointName) {
+    return (action) => action?.meta?.arg?.endpointName === endpointName;
+  }
+  function buildMatchThunkActions(thunk, endpointName) {
+    return {
+      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
+      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
+      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
+    };
+  }
+  return {
+    queryThunk,
+    mutationThunk,
+    infiniteQueryThunk,
+    prefetch,
+    updateQueryData,
+    upsertQueryData,
+    patchQueryData,
+    buildMatchThunkActions
+  };
+}
+function getNextPageParam(options, {
+  pages,
+  pageParams
+}, queryArg) {
+  const lastIndex = pages.length - 1;
+  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);
+}
+function getPreviousPageParam(options, {
+  pages,
+  pageParams
+}, queryArg) {
+  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);
+}
+function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
+  return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
+}
+
+// src/query/utils/getCurrent.ts
+function getCurrent(value) {
+  return isDraft(value) ? current(value) : value;
+}
+
+// src/query/core/buildSlice.ts
+function updateQuerySubstateIfExists(state, queryCacheKey, update) {
+  const substate = state[queryCacheKey];
+  if (substate) {
+    update(substate);
+  }
+}
+function getMutationCacheKey(id) {
+  return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
+}
+function updateMutationSubstateIfExists(state, id, update) {
+  const substate = state[getMutationCacheKey(id)];
+  if (substate) {
+    update(substate);
+  }
+}
+var initialState = {};
+function buildSlice({
+  reducerPath,
+  queryThunk,
+  mutationThunk,
+  serializeQueryArgs,
+  context: {
+    endpointDefinitions: definitions,
+    apiUid,
+    extractRehydrationInfo,
+    hasRehydrationInfo
+  },
+  assertTagType,
+  config
+}) {
+  const resetApiState = createAction(`${reducerPath}/resetApiState`);
+  function writePendingCacheEntry(draft, arg, upserting, meta) {
+    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 !== void 0) {
+        substate.originalArgs = arg.originalArgs;
+      }
+      substate.startedTimeStamp = meta.startedTimeStamp;
+      const endpointDefinition = definitions[meta.arg.endpointName];
+      if (isInfiniteQueryDefinition(endpointDefinition) && "direction" in arg) {
+        ;
+        substate.direction = arg.direction;
+      }
+    });
+  }
+  function writeFulfilledCacheEntry(draft, meta, payload, upserting) {
+    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
+      if (substate.requestId !== meta.requestId && !upserting) return;
+      const {
+        merge
+      } = definitions[meta.arg.endpointName];
+      substate.status = STATUS_FULFILLED;
+      if (merge) {
+        if (substate.data !== void 0) {
+          const {
+            fulfilledTimeStamp,
+            arg,
+            baseQueryMeta,
+            requestId
+          } = meta;
+          let newData = createNextState(substate.data, (draftSubstateData) => {
+            return merge(draftSubstateData, payload, {
+              arg: arg.originalArgs,
+              baseQueryMeta,
+              fulfilledTimeStamp,
+              requestId
+            });
+          });
+          substate.data = newData;
+        } else {
+          substate.data = payload;
+        }
+      } else {
+        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;
+      }
+      delete substate.error;
+      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
+    });
+  }
+  const querySlice = createSlice({
+    name: `${reducerPath}/queries`,
+    initialState,
+    reducers: {
+      removeQueryResult: {
+        reducer(draft, {
+          payload: {
+            queryCacheKey
+          }
+        }) {
+          delete draft[queryCacheKey];
+        },
+        prepare: prepareAutoBatched()
+      },
+      cacheEntriesUpserted: {
+        reducer(draft, action) {
+          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) => {
+          const queryDescriptions = payload.map((entry) => {
+            const {
+              endpointName,
+              arg,
+              value
+            } = entry;
+            const endpointDefinition = definitions[endpointName];
+            const queryDescription = {
+              type: ENDPOINT_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
+          }
+        }) {
+          updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
+            substate.data = applyPatches(substate.data, patches.concat());
+          });
+        },
+        prepare: prepareAutoBatched()
+      }
+    },
+    extraReducers(builder) {
+      builder.addCase(queryThunk.pending, (draft, {
+        meta,
+        meta: {
+          arg
+        }
+      }) => {
+        const upserting = isUpsertQuery(arg);
+        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) {
+          } else {
+            if (substate.requestId !== requestId) return;
+            substate.status = STATUS_REJECTED;
+            substate.error = payload ?? error;
+          }
+        });
+      }).addMatcher(hasRehydrationInfo, (draft, action) => {
+        const {
+          queries
+        } = extractRehydrationInfo(action);
+        for (const [key, entry] of Object.entries(queries)) {
+          if (
+            // do not rehydrate entries that were currently in flight.
+            entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED
+          ) {
+            draft[key] = entry;
+          }
+        }
+      });
+    }
+  });
+  const mutationSlice = createSlice({
+    name: `${reducerPath}/mutations`,
+    initialState,
+    reducers: {
+      removeMutationResult: {
+        reducer(draft, {
+          payload
+        }) {
+          const cacheKey = getMutationCacheKey(payload);
+          if (cacheKey in draft) {
+            delete draft[cacheKey];
+          }
+        },
+        prepare: prepareAutoBatched()
+      }
+    },
+    extraReducers(builder) {
+      builder.addCase(mutationThunk.pending, (draft, {
+        meta,
+        meta: {
+          requestId,
+          arg,
+          startedTimeStamp
+        }
+      }) => {
+        if (!arg.track) return;
+        draft[getMutationCacheKey(meta)] = {
+          requestId,
+          status: 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;
+        });
+      }).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;
+          }
+        }
+      });
+    }
+  });
+  const initialInvalidationState = {
+    tags: {},
+    keys: {}
+  };
+  const invalidationSlice = createSlice({
+    name: `${reducerPath}/invalidation`,
+    initialState: initialInvalidationState,
+    reducers: {
+      updateProvidedBy: {
+        reducer(draft, action) {
+          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);
+              }
+            }
+            draft.keys[queryCacheKey] = providedTags;
+          }
+        },
+        prepare: prepareAutoBatched()
+      }
+    },
+    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 = action.payload.map(({
+          queryDescription,
+          value
+        }) => {
+          return {
+            type: "UNKNOWN",
+            payload: value,
+            meta: {
+              requestStatus: "fulfilled",
+              requestId: "UNKNOWN",
+              arg: queryDescription
+            }
+          };
+        });
+        writeProvidedTagsForQueries(draft, mockActions);
+      });
+    }
+  });
+  function removeCacheKeyFromTags(draft, queryCacheKey) {
+    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);
+    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, actions3) {
+    const providedByEntries = actions3.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));
+  }
+  const subscriptionSlice = createSlice({
+    name: `${reducerPath}/subscriptions`,
+    initialState,
+    reducers: {
+      updateSubscriptionOptions(d, a) {
+      },
+      unsubscribeQueryResult(d, a) {
+      },
+      internal_getRTKQSubscriptions() {
+      }
+    }
+  });
+  const internalSubscriptionsSlice = createSlice({
+    name: `${reducerPath}/internalSubscriptions`,
+    initialState,
+    reducers: {
+      subscriptionsUpdated: {
+        reducer(state, action) {
+          return applyPatches(state, action.payload);
+        },
+        prepare: prepareAutoBatched()
+      }
+    }
+  });
+  const configSlice = createSlice({
+    name: `${reducerPath}/config`,
+    initialState: {
+      online: isOnline(),
+      focused: isDocumentVisible(),
+      middlewareRegistered: false,
+      ...config
+    },
+    reducers: {
+      middlewareRegistered(state, {
+        payload
+      }) {
+        state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
+      }
+    },
+    extraReducers: (builder) => {
+      builder.addCase(onOnline, (state) => {
+        state.online = true;
+      }).addCase(onOffline, (state) => {
+        state.online = false;
+      }).addCase(onFocus, (state) => {
+        state.focused = true;
+      }).addCase(onFocusLost, (state) => {
+        state.focused = false;
+      }).addMatcher(hasRehydrationInfo, (draft) => ({
+        ...draft
+      }));
+    }
+  });
+  const combinedReducer = combineReducers({
+    queries: querySlice.reducer,
+    mutations: mutationSlice.reducer,
+    provided: invalidationSlice.reducer,
+    subscriptions: internalSubscriptionsSlice.reducer,
+    config: configSlice.reducer
+  });
+  const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
+  const actions2 = {
+    ...configSlice.actions,
+    ...querySlice.actions,
+    ...subscriptionSlice.actions,
+    ...internalSubscriptionsSlice.actions,
+    ...mutationSlice.actions,
+    ...invalidationSlice.actions,
+    resetApiState
+  };
+  return {
+    reducer,
+    actions: actions2
+  };
+}
+
+// src/query/core/buildSelectors.ts
+var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
+var initialSubState = {
+  status: STATUS_UNINITIALIZED
+};
+var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => {
+});
+var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, () => {
+});
+function buildSelectors({
+  serializeQueryArgs,
+  reducerPath,
+  createSelector: createSelector2
+}) {
+  const selectSkippedQuery = (state) => defaultQuerySubState;
+  const selectSkippedMutation = (state) => defaultMutationSubState;
+  return {
+    buildQuerySelector,
+    buildInfiniteQuerySelector,
+    buildMutationSelector,
+    selectInvalidatedBy,
+    selectCachedArgsForQuery,
+    selectApiState,
+    selectQueries,
+    selectMutations,
+    selectQueryEntry,
+    selectConfig
+  };
+  function withRequestFlags(substate) {
+    return {
+      ...substate,
+      ...getRequestStatusFlags(substate.status)
+    };
+  }
+  function selectApiState(rootState) {
+    const state = rootState[reducerPath];
+    if (process.env.NODE_ENV !== "production") {
+      if (!state) {
+        if (selectApiState.triggered) return state;
+        selectApiState.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) {
+    return selectApiState(rootState)?.queries;
+  }
+  function selectQueryEntry(rootState, cacheKey) {
+    return selectQueries(rootState)?.[cacheKey];
+  }
+  function selectMutations(rootState) {
+    return selectApiState(rootState)?.mutations;
+  }
+  function selectConfig(rootState) {
+    return selectApiState(rootState)?.config;
+  }
+  function buildAnyQuerySelector(endpointName, endpointDefinition, combiner) {
+    return (queryArgs) => {
+      if (queryArgs === skipToken) {
+        return createSelector2(selectSkippedQuery, combiner);
+      }
+      const serializedArgs = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName
+      });
+      const selectQuerySubstate = (state) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;
+      return createSelector2(selectQuerySubstate, combiner);
+    };
+  }
+  function buildQuerySelector(endpointName, endpointDefinition) {
+    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags);
+  }
+  function buildInfiniteQuerySelector(endpointName, endpointDefinition) {
+    const {
+      infiniteQueryOptions
+    } = endpointDefinition;
+    function withInfiniteQueryResultFlags(substate) {
+      const stateWithRequestFlags = {
+        ...substate,
+        ...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);
+  }
+  function buildMutationSelector() {
+    return (id) => {
+      let mutationId;
+      if (typeof id === "object") {
+        mutationId = getMutationCacheKey(id) ?? skipToken;
+      } else {
+        mutationId = id;
+      }
+      const selectMutationSubstate = (state) => selectApiState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
+      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
+      return createSelector2(finalSelectMutationSubstate, withRequestFlags);
+    };
+  }
+  function selectInvalidatedBy(state, tags) {
+    const apiState = state[reducerPath];
+    const toInvalidate = /* @__PURE__ */ new Set();
+    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 !== void 0 ? (
+        // 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(state, queryName) {
+    return filterMap(Object.values(selectQueries(state)), (entry) => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
+  }
+  function getHasNextPage(options, data, queryArg) {
+    if (!data) return false;
+    return getNextPageParam(options, data, queryArg) != null;
+  }
+  function getHasPreviousPage(options, data, queryArg) {
+    if (!data || !options.getPreviousPageParam) return false;
+    return getPreviousPageParam(options, data, queryArg) != null;
+  }
+}
+
+// src/query/createApi.ts
+import { formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage22, formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
+
+// src/query/defaultSerializeQueryArgs.ts
+var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
+var defaultSerializeQueryArgs = ({
+  endpointName,
+  queryArgs
+}) => {
+  let serialized = "";
+  const cached = cache?.get(queryArgs);
+  if (typeof cached === "string") {
+    serialized = cached;
+  } else {
+    const stringified = JSON.stringify(queryArgs, (key, value) => {
+      value = typeof value === "bigint" ? {
+        $bigint: value.toString()
+      } : value;
+      value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
+        acc[key2] = value[key2];
+        return acc;
+      }, {}) : value;
+      return value;
+    });
+    if (isPlainObject(queryArgs)) {
+      cache?.set(queryArgs, stringified);
+    }
+    serialized = stringified;
+  }
+  return `${endpointName}(${serialized})`;
+};
+
+// src/query/createApi.ts
+import { weakMapMemoize } from "reselect";
+function buildCreateApi(...modules) {
+  return function baseCreateApi(options) {
+    const extractRehydrationInfo = weakMapMemoize((action) => options.extractRehydrationInfo?.(action, {
+      reducerPath: options.reducerPath ?? "api"
+    }));
+    const optionsWithDefaults = {
+      reducerPath: "api",
+      keepUnusedDataFor: 60,
+      refetchOnMountOrArgChange: false,
+      refetchOnFocus: false,
+      refetchOnReconnect: false,
+      invalidationBehavior: "delayed",
+      ...options,
+      extractRehydrationInfo,
+      serializeQueryArgs(queryArgsApi) {
+        let finalSerializeQueryArgs = defaultSerializeQueryArgs;
+        if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
+          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
+          finalSerializeQueryArgs = (queryArgsApi2) => {
+            const initialResult = endpointSQA(queryArgsApi2);
+            if (typeof initialResult === "string") {
+              return initialResult;
+            } else {
+              return defaultSerializeQueryArgs({
+                ...queryArgsApi2,
+                queryArgs: initialResult
+              });
+            }
+          };
+        } else if (options.serializeQueryArgs) {
+          finalSerializeQueryArgs = options.serializeQueryArgs;
+        }
+        return finalSerializeQueryArgs(queryArgsApi);
+      },
+      tagTypes: [...options.tagTypes || []]
+    };
+    const context = {
+      endpointDefinitions: {},
+      batch(fn) {
+        fn();
+      },
+      apiUid: nanoid(),
+      extractRehydrationInfo,
+      hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null)
+    };
+    const api = {
+      injectEndpoints,
+      enhanceEndpoints({
+        addTagTypes,
+        endpoints
+      }) {
+        if (addTagTypes) {
+          for (const eT of addTagTypes) {
+            if (!optionsWithDefaults.tagTypes.includes(eT)) {
+              ;
+              optionsWithDefaults.tagTypes.push(eT);
+            }
+          }
+        }
+        if (endpoints) {
+          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
+            if (typeof partialDefinition === "function") {
+              partialDefinition(getEndpointDefinition(context, endpointName));
+            } else {
+              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
+            }
+          }
+        }
+        return api;
+      }
+    };
+    const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
+    function injectEndpoints(inject) {
+      const evaluatedEndpoints = inject.endpoints({
+        query: (x) => ({
+          ...x,
+          type: ENDPOINT_QUERY
+        }),
+        mutation: (x) => ({
+          ...x,
+          type: ENDPOINT_MUTATION
+        }),
+        infiniteQuery: (x) => ({
+          ...x,
+          type: ENDPOINT_INFINITEQUERY
+        })
+      });
+      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
+        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
+          if (inject.overrideExisting === "throw") {
+            throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(39) : `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: getPreviousPageParam2
+            } = infiniteQueryOptions;
+            if (typeof maxPages === "number") {
+              if (maxPages < 1) {
+                throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage22(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);
+              }
+              if (typeof getPreviousPageParam2 !== "function") {
+                throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(41) : `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;
+    }
+    return api.injectEndpoints({
+      endpoints: options.endpoints
+    });
+  };
+}
+
+// src/query/fakeBaseQuery.ts
+import { formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
+var _NEVER = /* @__PURE__ */ Symbol();
+function fakeBaseQuery() {
+  return function() {
+    throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
+  };
+}
+
+// src/query/tsHelpers.ts
+function assertCast(v) {
+}
+function safeAssign(target, ...args) {
+  return Object.assign(target, ...args);
+}
+
+// src/query/core/buildMiddleware/batchActions.ts
+var buildBatchedActionsHandler = ({
+  api,
+  queryThunk,
+  internalState,
+  mwApi
+}) => {
+  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
+  let previousSubscriptions = null;
+  let updateSyncTimer = null;
+  const {
+    updateSubscriptionOptions,
+    unsubscribeQueryResult
+  } = api.internalActions;
+  const actuallyMutateSubscriptions = (currentSubscriptions, 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) => {
+    const subscriptions = getSubscriptions();
+    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);
+    return subscriptionsForQueryArg?.size ?? 0;
+  };
+  const isRequestSubscribed = (queryCacheKey, requestId) => {
+    const subscriptions = getSubscriptions();
+    return !!subscriptions?.get(queryCacheKey)?.get(requestId);
+  };
+  const subscriptionSelectors = {
+    getSubscriptions,
+    getSubscriptionCount,
+    isRequestSubscribed
+  };
+  function serializeSubscriptions(currentSubscriptions) {
+    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));
+  }
+  return (action, mwApi2) => {
+    if (!previousSubscriptions) {
+      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
+    }
+    if (api.util.resetApiState.match(action)) {
+      previousSubscriptions = {};
+      internalState.currentSubscriptions.clear();
+      updateSyncTimer = null;
+      return [true, false];
+    }
+    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
+      return [false, subscriptionSelectors];
+    }
+    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
+    let actionShouldContinue = true;
+    if (process.env.NODE_ENV === "test" && typeof action.type === "string" && action.type === `${api.reducerPath}/getPolling`) {
+      return [false, internalState.currentPolls];
+    }
+    if (didMutate) {
+      if (!updateSyncTimer) {
+        updateSyncTimer = setTimeout(() => {
+          const newSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
+          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);
+          mwApi2.next(api.internalActions.subscriptionsUpdated(patches));
+          previousSubscriptions = newSubscriptions;
+          updateSyncTimer = null;
+        }, 500);
+      }
+      const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
+      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
+      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
+    }
+    return [actionShouldContinue, false];
+  };
+};
+
+// src/query/core/buildMiddleware/cacheCollection.ts
+var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
+var buildCacheCollectionHandler = ({
+  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) {
+    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);
+    if (!subscriptions) {
+      return false;
+    }
+    const hasSubscriptions = subscriptions.size > 0;
+    return hasSubscriptions;
+  }
+  const currentRemovalTimeouts = {};
+  function abortAllPromises(promiseMap) {
+    for (const promise of promiseMap.values()) {
+      promise?.abort?.();
+    }
+  }
+  const handler = (action, mwApi2) => {
+    const state = mwApi2.getState();
+    const config = selectConfig(state);
+    if (canTriggerUnsubscribe(action)) {
+      let queryCacheKeys;
+      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, mwApi2, 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);
+      handleUnsubscribeMany(Object.keys(queries), mwApi2, config);
+    }
+  };
+  function handleUnsubscribeMany(cacheKeys, api2, config) {
+    const state = api2.getState();
+    for (const queryCacheKey of cacheKeys) {
+      const entry = selectQueryEntry(state, queryCacheKey);
+      if (entry?.endpointName) {
+        handleUnsubscribe(queryCacheKey, entry.endpointName, api2, config);
+      }
+    }
+  }
+  function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName);
+    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
+    if (keepUnusedDataFor === Infinity) {
+      return;
+    }
+    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
+    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+      const currentTimeout = currentRemovalTimeouts[queryCacheKey];
+      if (currentTimeout) {
+        clearTimeout(currentTimeout);
+      }
+      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
+        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+          const entry = selectQueryEntry(api2.getState(), queryCacheKey);
+          if (entry?.endpointName) {
+            const runningQuery = api2.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));
+            runningQuery?.abort();
+          }
+          api2.dispatch(removeQueryResult({
+            queryCacheKey
+          }));
+        }
+        delete currentRemovalTimeouts[queryCacheKey];
+      }, finalKeepUnusedDataFor * 1e3);
+    }
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/cacheLifecycle.ts
+var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
+var buildCacheLifecycleHandler = ({
+  api,
+  reducerPath,
+  context,
+  queryThunk,
+  mutationThunk,
+  internalState,
+  selectors: {
+    selectQueryEntry,
+    selectApiState
+  }
+}) => {
+  const isQueryThunk = isAsyncThunkAction(queryThunk);
+  const isMutationThunk = isAsyncThunkAction(mutationThunk);
+  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
+  const lifecycleMap = {};
+  const {
+    removeQueryResult,
+    removeMutationResult,
+    cacheEntriesUpserted
+  } = api.internalActions;
+  function resolveLifecycleEntry(cacheKey, data, meta) {
+    const lifecycle = lifecycleMap[cacheKey];
+    if (lifecycle?.valueResolved) {
+      lifecycle.valueResolved({
+        data,
+        meta
+      });
+      delete lifecycle.valueResolved;
+    }
+  }
+  function removeLifecycleEntry(cacheKey) {
+    const lifecycle = lifecycleMap[cacheKey];
+    if (lifecycle) {
+      delete lifecycleMap[cacheKey];
+      lifecycle.cacheEntryRemoved();
+    }
+  }
+  function getActionMetaFields(action) {
+    const {
+      arg,
+      requestId
+    } = action.meta;
+    const {
+      endpointName,
+      originalArgs
+    } = arg;
+    return [endpointName, originalArgs, requestId];
+  }
+  const handler = (action, mwApi, stateBefore) => {
+    const cacheKey = getCacheKey(action);
+    function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
+      const oldEntry = selectQueryEntry(stateBefore, cacheKey2);
+      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey2);
+      if (!oldEntry && newEntry) {
+        handleNewKey(endpointName, originalArgs, cacheKey2, 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 cacheKey2 of Object.keys(lifecycleMap)) {
+        removeLifecycleEntry(cacheKey2);
+      }
+    }
+  };
+  function getCacheKey(action) {
+    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, originalArgs, queryCacheKey, mwApi, requestId) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName);
+    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
+    if (!onCacheEntryAdded) return;
+    const lifecycle = {};
+    const cacheEntryRemoved = new Promise((resolve) => {
+      lifecycle.cacheEntryRemoved = resolve;
+    });
+    const cacheDataLoaded = Promise.race([new Promise((resolve) => {
+      lifecycle.valueResolved = resolve;
+    }), cacheEntryRemoved.then(() => {
+      throw neverResolvedError;
+    })]);
+    cacheDataLoaded.catch(() => {
+    });
+    lifecycleMap[queryCacheKey] = lifecycle;
+    const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);
+    const extra = mwApi.dispatch((_, __, extra2) => extra2);
+    const lifecycleApi = {
+      ...mwApi,
+      getCacheEntry: () => selector(mwApi.getState()),
+      requestId,
+      extra,
+      updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
+      cacheDataLoaded,
+      cacheEntryRemoved
+    };
+    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
+    Promise.resolve(runningHandler).catch((e) => {
+      if (e === neverResolvedError) return;
+      throw e;
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/devMiddleware.ts
+var buildDevCheckHandler = ({
+  api,
+  context: {
+    apiUid
+  },
+  reducerPath
+}) => {
+  return (action, mwApi) => {
+    if (api.util.resetApiState.match(action)) {
+      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
+    }
+    if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
+        console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
+You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
+      }
+    }
+  };
+};
+
+// src/query/core/buildMiddleware/invalidationByTags.ts
+var buildInvalidationByTagsHandler = ({
+  reducerPath,
+  context,
+  context: {
+    endpointDefinitions
+  },
+  mutationThunk,
+  queryThunk,
+  api,
+  assertTagType,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    removeQueryResult
+  } = api.internalActions;
+  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
+  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));
+  let pendingTagInvalidations = [];
+  let pendingRequestCount = 0;
+  const handler = (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, void 0, void 0, void 0, void 0, assertTagType), mwApi);
+    }
+  };
+  function hasPendingRequests() {
+    return pendingRequestCount > 0;
+  }
+  function invalidateTags(newTags, mwApi) {
+    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
+            }));
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            mwApi.dispatch(refetchQuery(querySubState));
+          }
+        }
+      }
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/polling.ts
+var buildPollingHandler = ({
+  reducerPath,
+  queryThunk,
+  api,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    currentPolls,
+    currentSubscriptions
+  } = internalState;
+  const pendingPollingUpdates = /* @__PURE__ */ new Set();
+  let pollingUpdateTimer = null;
+  const handler = (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();
+      if (pollingUpdateTimer) {
+        clearTimeout(pollingUpdateTimer);
+        pollingUpdateTimer = null;
+      }
+      pendingPollingUpdates.clear();
+    }
+  };
+  function schedulePollingUpdate(queryCacheKey, api2) {
+    pendingPollingUpdates.add(queryCacheKey);
+    if (!pollingUpdateTimer) {
+      pollingUpdateTimer = setTimeout(() => {
+        for (const key of pendingPollingUpdates) {
+          updatePollingInterval({
+            queryCacheKey: key
+          }, api2);
+        }
+        pendingPollingUpdates.clear();
+        pollingUpdateTimer = null;
+      }, 0);
+    }
+  }
+  function startNextPoll({
+    queryCacheKey
+  }, api2) {
+    const state = api2.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 = void 0;
+    }
+    const nextPollTimestamp = Date.now() + lowestPollingInterval;
+    currentPolls.set(queryCacheKey, {
+      nextPollTimestamp,
+      pollingInterval: lowestPollingInterval,
+      timeout: setTimeout(() => {
+        if (state.config.focused || !skipPollingIfUnfocused) {
+          api2.dispatch(refetchQuery(querySubState));
+        }
+        startNextPoll({
+          queryCacheKey
+        }, api2);
+      }, lowestPollingInterval)
+    });
+  }
+  function updatePollingInterval({
+    queryCacheKey
+  }, api2) {
+    const state = api2.getState()[reducerPath];
+    const querySubState = state.queries[queryCacheKey];
+    const subscriptions = currentSubscriptions.get(queryCacheKey);
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
+      return;
+    }
+    const {
+      lowestPollingInterval
+    } = findLowestPollingInterval(subscriptions);
+    if (process.env.NODE_ENV === "test") {
+      const updateCounters = currentPolls.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
+      }, api2);
+    }
+  }
+  function cleanupPollForKey(key) {
+    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 = /* @__PURE__ */ new Map()) {
+    let skipPollingIfUnfocused = 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;
+};
+
+// src/query/core/buildMiddleware/queryLifecycle.ts
+var buildQueryLifecycleHandler = ({
+  api,
+  context,
+  queryThunk,
+  mutationThunk
+}) => {
+  const isPendingThunk = isPending(queryThunk, mutationThunk);
+  const isRejectedThunk = isRejected(queryThunk, mutationThunk);
+  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);
+  const lifecycleMap = {};
+  const handler = (action, mwApi) => {
+    if (isPendingThunk(action)) {
+      const {
+        requestId,
+        arg: {
+          endpointName,
+          originalArgs
+        }
+      } = action.meta;
+      const endpointDefinition = getEndpointDefinition(context, endpointName);
+      const onQueryStarted = endpointDefinition?.onQueryStarted;
+      if (onQueryStarted) {
+        const lifecycle = {};
+        const queryFulfilled = new Promise((resolve, reject) => {
+          lifecycle.resolve = resolve;
+          lifecycle.reject = reject;
+        });
+        queryFulfilled.catch(() => {
+        });
+        lifecycleMap[requestId] = lifecycle;
+        const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);
+        const extra = mwApi.dispatch((_, __, extra2) => extra2);
+        const lifecycleApi = {
+          ...mwApi,
+          getCacheEntry: () => selector(mwApi.getState()),
+          requestId,
+          extra,
+          updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
+          queryFulfilled
+        };
+        onQueryStarted(originalArgs, lifecycleApi);
+      }
+    } else if (isFullfilledThunk(action)) {
+      const {
+        requestId,
+        baseQueryMeta
+      } = action.meta;
+      lifecycleMap[requestId]?.resolve({
+        data: action.payload,
+        meta: baseQueryMeta
+      });
+      delete lifecycleMap[requestId];
+    } else if (isRejectedThunk(action)) {
+      const {
+        requestId,
+        rejectedWithValue,
+        baseQueryMeta
+      } = action.meta;
+      lifecycleMap[requestId]?.reject({
+        error: action.payload ?? action.error,
+        isUnhandledError: !rejectedWithValue,
+        meta: baseQueryMeta
+      });
+      delete lifecycleMap[requestId];
+    }
+  };
+  return handler;
+};
+
+// src/query/core/buildMiddleware/windowEventHandling.ts
+var buildWindowEventHandler = ({
+  reducerPath,
+  context,
+  api,
+  refetchQuery,
+  internalState
+}) => {
+  const {
+    removeQueryResult
+  } = api.internalActions;
+  const handler = (action, mwApi) => {
+    if (onFocus.match(action)) {
+      refetchValidQueries(mwApi, "refetchOnFocus");
+    }
+    if (onOnline.match(action)) {
+      refetchValidQueries(mwApi, "refetchOnReconnect");
+    }
+  };
+  function refetchValidQueries(api2, type) {
+    const state = api2.getState()[reducerPath];
+    const queries = state.queries;
+    const subscriptions = internalState.currentSubscriptions;
+    context.batch(() => {
+      for (const queryCacheKey of 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] === void 0) && state.config[type];
+        if (shouldRefetch) {
+          if (subscriptionSubState.size === 0) {
+            api2.dispatch(removeQueryResult({
+              queryCacheKey
+            }));
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            api2.dispatch(refetchQuery(querySubState));
+          }
+        }
+      }
+    });
+  }
+  return handler;
+};
+
+// src/query/core/buildMiddleware/index.ts
+function buildMiddleware(input) {
+  const {
+    reducerPath,
+    queryThunk,
+    api,
+    context,
+    getInternalState
+  } = input;
+  const {
+    apiUid
+  } = context;
+  const actions2 = {
+    invalidateTags: createAction(`${reducerPath}/invalidateTags`)
+  };
+  const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
+  const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
+  const middleware = (mwApi) => {
+    let initialized2 = false;
+    const internalState = getInternalState(mwApi.dispatch);
+    const builderArgs = {
+      ...input,
+      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 (!initialized2) {
+          initialized2 = true;
+          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
+        }
+        const mwApiWithNext = {
+          ...mwApi,
+          next
+        };
+        const stateBefore = mwApi.getState();
+        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
+        let res;
+        if (actionShouldContinue) {
+          res = next(action);
+        } else {
+          res = internalProbeResult;
+        }
+        if (!!mwApi.getState()[reducerPath]) {
+          windowEventsHandler(action, mwApiWithNext, stateBefore);
+          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
+            for (const handler of handlers) {
+              handler(action, mwApiWithNext, stateBefore);
+            }
+          }
+        }
+        return res;
+      };
+    };
+  };
+  return {
+    middleware,
+    actions: actions2
+  };
+  function refetchQuery(querySubState) {
+    return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
+      subscribe: false,
+      forceRefetch: true
+    });
+  }
+}
+
+// src/query/core/module.ts
+var coreModuleName = /* @__PURE__ */ Symbol();
+var coreModule = ({
+  createSelector: createSelector2 = createSelector
+} = {}) => ({
+  name: coreModuleName,
+  init(api, {
+    baseQuery,
+    tagTypes,
+    reducerPath,
+    serializeQueryArgs,
+    keepUnusedDataFor,
+    refetchOnMountOrArgChange,
+    refetchOnFocus,
+    refetchOnReconnect,
+    invalidationBehavior,
+    onSchemaFailure,
+    catchSchemaFailure,
+    skipSchemaValidation
+  }, context) {
+    enablePatches();
+    assertCast(serializeQueryArgs);
+    const assertTagType = (tag) => {
+      if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+        if (!tagTypes.includes(tag.type)) {
+          console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
+        }
+      }
+      return tag;
+    };
+    Object.assign(api, {
+      reducerPath,
+      endpoints: {},
+      internalActions: {
+        onOnline,
+        onOffline,
+        onFocus,
+        onFocusLost
+      },
+      util: {}
+    });
+    const selectors = buildSelectors({
+      serializeQueryArgs,
+      reducerPath,
+      createSelector: createSelector2
+    });
+    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
+    });
+    safeAssign(api.internalActions, sliceActions);
+    const internalStateMap = /* @__PURE__ */ new WeakMap();
+    const getInternalState = (dispatch) => {
+      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
+        currentSubscriptions: /* @__PURE__ */ new Map(),
+        currentPolls: /* @__PURE__ */ new Map(),
+        runningQueries: /* @__PURE__ */ new Map(),
+        runningMutations: /* @__PURE__ */ new Map()
+      }));
+      return state;
+    };
+    const {
+      buildInitiateQuery,
+      buildInitiateInfiniteQuery,
+      buildInitiateMutation,
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueriesThunk,
+      getRunningQueryThunk
+    } = buildInitiate({
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      serializeQueryArgs,
+      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,
+      middleware
+    });
+    return {
+      name: coreModuleName,
+      injectEndpoint(endpointName, definition) {
+        const anyApi = api;
+        const endpoint = anyApi.endpoints[endpointName] ??= {};
+        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));
+        }
+      }
+    };
+  }
+});
+
+// src/query/core/index.ts
+var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
+export {
+  NamedSchemaError,
+  QueryStatus,
+  _NEVER,
+  buildCreateApi,
+  copyWithStructuralSharing,
+  coreModule,
+  coreModuleName,
+  createApi,
+  defaultSerializeQueryArgs,
+  fakeBaseQuery,
+  fetchBaseQuery,
+  retry,
+  setupListeners,
+  skipToken
+};
+//# sourceMappingURL=rtk-query.modern.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/query/rtk-query.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/query/core/apiState.ts","../../src/query/core/rtkImports.ts","../../src/query/utils/copyWithStructuralSharing.ts","../../src/query/utils/filterMap.ts","../../src/query/utils/isAbsoluteUrl.ts","../../src/query/utils/isDocumentVisible.ts","../../src/query/utils/isNotNullish.ts","../../src/query/utils/isOnline.ts","../../src/query/utils/joinUrls.ts","../../src/query/utils/getOrInsert.ts","../../src/query/utils/signals.ts","../../src/query/fetchBaseQuery.ts","../../src/query/HandledError.ts","../../src/query/retry.ts","../../src/query/core/setupListeners.ts","../../src/query/endpointDefinitions.ts","../../src/query/utils/immerImports.ts","../../src/query/core/buildInitiate.ts","../../src/tsHelpers.ts","../../src/query/apiTypes.ts","../../src/query/standardSchema.ts","../../src/query/core/buildThunks.ts","../../src/query/utils/getCurrent.ts","../../src/query/core/buildSlice.ts","../../src/query/core/buildSelectors.ts","../../src/query/createApi.ts","../../src/query/defaultSerializeQueryArgs.ts","../../src/query/fakeBaseQuery.ts","../../src/query/tsHelpers.ts","../../src/query/core/buildMiddleware/batchActions.ts","../../src/query/core/buildMiddleware/cacheCollection.ts","../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../src/query/core/buildMiddleware/devMiddleware.ts","../../src/query/core/buildMiddleware/invalidationByTags.ts","../../src/query/core/buildMiddleware/polling.ts","../../src/query/core/buildMiddleware/queryLifecycle.ts","../../src/query/core/buildMiddleware/windowEventHandling.ts","../../src/query/core/buildMiddleware/index.ts","../../src/query/core/module.ts","../../src/query/core/index.ts"],"sourcesContent":["import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, FullTagDescription, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFromAnyQuery, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n  _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n  queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n  requestId: string;\n  fixedCacheKey?: string;\n} | {\n  requestId?: string;\n  fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number;\n  refetchOnReconnect: boolean;\n  refetchOnFocus: boolean;\n};\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam;\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (lastPage: DataType, allPages: Array<DataType>, lastPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>, queryArg: QueryArg) => PageParam | undefined | null;\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number;\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   */\n  refetchCachedPages?: boolean;\n};\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>;\n  pageParams: Array<PageParam>;\n};\n\n// NOTE: DO NOT import and use this for runtime comparisons internally,\n// except in the RTKQ React package. Use the string versions just below this.\n// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated\n// constants like \"initialized\":\n// https://github.com/evanw/esbuild/releases/tag/v0.14.7\n// We still have to use this in the React package since we don't publicly export\n// the string constants below.\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\n\n// Use these string constants for runtime comparisons internally\nexport const STATUS_UNINITIALIZED = QueryStatus.uninitialized;\nexport const STATUS_PENDING = QueryStatus.pending;\nexport const STATUS_FULFILLED = QueryStatus.fulfilled;\nexport const STATUS_REJECTED = QueryStatus.rejected;\nexport type RequestStatusFlags = {\n  status: QueryStatus.uninitialized;\n  isUninitialized: true;\n  isLoading: false;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.pending;\n  isUninitialized: false;\n  isLoading: true;\n  isSuccess: false;\n  isError: false;\n} | {\n  status: QueryStatus.fulfilled;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: true;\n  isError: false;\n} | {\n  status: QueryStatus.rejected;\n  isUninitialized: false;\n  isLoading: false;\n  isSuccess: false;\n  isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === STATUS_UNINITIALIZED,\n    isLoading: status === STATUS_PENDING,\n    isSuccess: status === STATUS_FULFILLED,\n    isError: status === STATUS_REJECTED\n  } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\nexport type SubscribersInternal = Map<string, SubscriptionOptions>;\nexport type Subscribers = {\n  [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>;\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string;\n  /**\n   * The received data from the query\n   */\n  data?: DataType;\n  /**\n   * The received error if applicable\n   */\n  error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string;\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number;\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n  error: undefined;\n}) | ({\n  status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n  status: QueryStatus.uninitialized;\n  originalArgs?: undefined;\n  data?: undefined;\n  error?: undefined;\n  requestId?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n  direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = {\n  requestId: string;\n  data?: ResultTypeFrom<D>;\n  error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n  endpointName: string;\n  startedTimeStamp: number;\n  fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any, any>> = (({\n  status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n  error: undefined;\n}) | (({\n  status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n  data?: undefined;\n}) | ({\n  status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n  requestId?: undefined;\n  status: QueryStatus.uninitialized;\n  data?: undefined;\n  error?: undefined;\n  endpointName?: string;\n  startedTimeStamp?: undefined;\n  fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n  queries: QueryState<D>;\n  mutations: MutationState<D>;\n  provided: InvalidationState<E>;\n  subscriptions: SubscriptionState;\n  config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = {\n  tags: { [_ in TagTypes]: {\n    [id: string]: Array<QueryCacheKey>;\n    [id: number]: Array<QueryCacheKey>;\n  } };\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>;\n};\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionInternalState = Map<string, SubscribersInternal>;\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath;\n  online: boolean;\n  focused: boolean;\n  middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number;\n  invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from '@reduxjs/toolkit';","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n    return newObj;\n  }\n  const newKeys = Object.keys(newObj);\n  const oldKeys = Object.keys(oldObj);\n  let isSameObject = newKeys.length === oldKeys.length;\n  const mergeObj: any = Array.isArray(newObj) ? [] : {};\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n  }\n  return isSameObject ? oldObj : mergeObj;\n}","// Preserve type guard predicate behavior when passing to mapper\nexport 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[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[];\nexport function filterMap<T, U>(array: readonly T[], predicate: (item: T, index: number) => boolean, mapper: (item: T, index: number) => U | U[]): U[] {\n  return array.reduce<(U | U[])[]>((acc, item, i) => {\n    if (predicate(item as any, i)) {\n      acc.push(mapper(item as any, i));\n    }\n    return acc;\n  }, []).flat() as U[];\n}","/**\n * If either :// or // is present consider it to be an absolute url\n *\n * @param url string\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url);\n}","/**\n * Assumes true for a non-browser env, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true;\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null;\n}\nexport function filterNullishValues<T>(map?: Map<any, T>) {\n  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[];\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n  if (!base) {\n    return url!;\n  }\n  if (!url) {\n    return base;\n  }\n  if (isAbsoluteUrl(url)) {\n    return url;\n  }\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n  base = withoutTrailingSlash(base);\n  url = withoutLeadingSlash(url);\n  return `${base}${delimiter}${url}`;\n}","// Duplicate some of the utils in `/src/utils` to ensure\n// we don't end up dragging in larger chunks of the RTK core\n// into the RTKQ bundle\n\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport const createNewMap = () => new Map();","// AbortSignal.timeout() is currently baseline 2024\nexport const timeoutSignal = (milliseconds: number) => {\n  const abortController = new AbortController();\n  setTimeout(() => {\n    const message = 'signal timed out';\n    const name = 'TimeoutError';\n    abortController.abort(\n    // some environments (React Native, Node) don't have DOMException\n    typeof DOMException !== 'undefined' ? new DOMException(message, name) : Object.assign(new Error(message), {\n      name\n    }));\n  }, milliseconds);\n  return abortController.signal;\n};\n\n// AbortSignal.any() is currently baseline 2024\nexport const anySignal = (...signals: AbortSignal[]) => {\n  // if any are already aborted, return an already aborted signal\n  for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);\n\n  // otherwise, create a new signal that aborts when any of the given signals abort\n  const abortController = new AbortController();\n  for (const signal of signals) {\n    signal.addEventListener('abort', () => abortController.abort(signal.reason), {\n      signal: abortController.signal,\n      once: true\n    });\n  }\n  return abortController.signal;\n};","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nimport { anySignal, timeoutSignal } from './utils/signals';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n  headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n  url: string;\n  params?: Record<string, any>;\n  body?: any;\n  responseHandler?: ResponseHandler;\n  validateStatus?: (response: Response, body: any) => boolean;\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n  /**\n   * * `number`:\n   *   HTTP status code\n   */\n  status: number;\n  data: unknown;\n} | {\n  /**\n   * * `\"FETCH_ERROR\"`:\n   *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n   **/\n  status: 'FETCH_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"PARSING_ERROR\"`:\n   *   An error happened during parsing.\n   *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n   *   or an error occurred while executing a custom `responseHandler`.\n   **/\n  status: 'PARSING_ERROR';\n  originalStatus: number;\n  data: string;\n  error: string;\n} | {\n  /**\n   * * `\"TIMEOUT_ERROR\"`:\n   *   Request timed out\n   **/\n  status: 'TIMEOUT_ERROR';\n  data?: undefined;\n  error: string;\n} | {\n  /**\n   * * `\"CUSTOM_ERROR\"`:\n   *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n   **/\n  status: 'CUSTOM_ERROR';\n  data?: unknown;\n  error: string;\n};\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj;\n  }\n  const copy: Record<string, any> = {\n    ...obj\n  };\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k];\n  }\n  return copy;\n}\n\n// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\nconst isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string;\n  prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n    arg: string | FetchArgs;\n    extraOptions: unknown;\n  }) => MaybePromise<Headers | void>;\n  fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n  paramsSerializer?: (params: Record<string, any>) => string;\n  /**\n   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean;\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string;\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n  request: Request;\n  response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = x => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n  }\n  return async (arg, api, extraOptions) => {\n    const {\n      getState,\n      extra,\n      endpoint,\n      forced,\n      type\n    } = api;\n    let meta: FetchBaseQueryMeta | undefined;\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? 'json' as const,\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? {\n      url: arg\n    } : arg;\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,\n      ...rest\n    };\n    headers = new Headers(stripUndefined(headers));\n    config.headers = (await prepareHeaders(headers, {\n      getState,\n      arg,\n      extra,\n      endpoint,\n      forced,\n      type,\n      extraOptions\n    })) || headers;\n    const bodyIsJsonifiable = isJsonifiable(config.body);\n\n    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically\n    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)\n    if (config.body != null && !bodyIsJsonifiable && typeof config.body !== 'string') {\n      config.headers.delete('content-type');\n    }\n    if (!config.headers.has('content-type') && bodyIsJsonifiable) {\n      config.headers.set('content-type', jsonContentType);\n    }\n    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer);\n    }\n\n    // Set Accept header based on responseHandler if not already set\n    if (!config.headers.has('accept')) {\n      if (responseHandler === 'json') {\n        config.headers.set('accept', 'application/json');\n      } else if (responseHandler === 'text') {\n        config.headers.set('accept', 'text/plain, text/html, */*');\n      }\n      // For 'content-type' responseHandler, don't set Accept (let server decide)\n    }\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?';\n      const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n      url += divider + query;\n    }\n    url = joinUrls(baseUrl, url);\n    const request = new Request(url, config);\n    const requestClone = new Request(url, config);\n    meta = {\n      request: requestClone\n    };\n    let response;\n    try {\n      response = await fetchFn(request);\n    } catch (e) {\n      return {\n        error: {\n          status: (e instanceof Error || typeof DOMException !== 'undefined' && e instanceof DOMException) && e.name === 'TimeoutError' ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n          error: String(e)\n        },\n        meta\n      };\n    }\n    const responseClone = response.clone();\n    meta.response = responseClone;\n    let resultData: any;\n    let responseText: string = '';\n    try {\n      let handleResponseError;\n      await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n      // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n      // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n      responseClone.text().then(r => responseText = r, () => {})]);\n      if (handleResponseError) throw handleResponseError;\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e)\n        },\n        meta\n      };\n    }\n    return validateStatus(response, resultData) ? {\n      data: resultData,\n      meta\n    } : {\n      error: {\n        status: response.status,\n        data: resultData\n      },\n      meta\n    };\n  };\n  async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response);\n    }\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n    }\n    if (responseHandler === 'json') {\n      const text = await response.text();\n      return text.length ? JSON.parse(text) : null;\n    }\n    return response.text();\n  }\n}","export class HandledError {\n  constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5, signal?: AbortSignal) {\n  const attempts = Math.min(attempt, maxRetries);\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n\n  await new Promise<void>((resolve, reject) => {\n    const timeoutId = setTimeout(() => resolve(), timeout);\n\n    // If signal is provided and gets aborted, clear timeout and reject\n    if (signal) {\n      const abortHandler = () => {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      };\n\n      // Check if already aborted\n      if (signal.aborted) {\n        clearTimeout(timeoutId);\n        reject(new Error('Aborted'));\n      } else {\n        signal.addEventListener('abort', abortHandler, {\n          once: true\n        });\n      }\n    }\n  });\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n  attempt: number;\n  baseQueryApi: BaseQueryApi;\n  extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (attempt: number, maxRetries: number, signal?: AbortSignal) => Promise<void>;\n} & ({\n  /**\n   * How many times the query will be retried (default: 5)\n   */\n  maxRetries?: number;\n  retryCondition?: undefined;\n} | {\n  /**\n   * Callback to determine if a retry should be attempted.\n   * Return `true` for another retry and `false` to quit trying prematurely.\n   */\n  retryCondition?: RetryConditionFunction;\n  maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n  throw Object.assign(new HandledError({\n    error,\n    meta\n  }), {\n    throwImmediately: true\n  });\n}\n\n/**\n * Checks if the abort signal is aborted and fails immediately if so.\n * Used to exit retry loops cleanly when a request is aborted.\n */\nfunction failIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    fail({\n      status: 'CUSTOM_ERROR',\n      error: 'Aborted'\n    });\n  }\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n  const [maxRetries] = possibleMaxRetries.slice(-1);\n  const defaultRetryCondition: RetryConditionFunction = (_, __, {\n    attempt\n  }) => attempt <= maxRetries;\n  const options: {\n    maxRetries: number;\n    backoff: typeof defaultBackoff;\n    retryCondition: typeof defaultRetryCondition;\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions\n  };\n  let retry = 0;\n  while (true) {\n    // Check if aborted before each attempt\n    failIfAborted(api.signal);\n    try {\n      const result = await baseQuery(args, api, extraOptions);\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result);\n      }\n      return result;\n    } catch (e: any) {\n      retry++;\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value;\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e;\n      }\n      if (e instanceof HandledError) {\n        if (!options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n          attempt: retry,\n          baseQueryApi: api,\n          extraOptions\n        })) {\n          return e.value; // Max retries for expected error\n        }\n      } else {\n        // For unexpected errors, respect maxRetries\n        if (retry > options.maxRetries) {\n          // Return the error as a proper error response instead of throwing\n          return {\n            error: e\n          };\n        }\n      }\n\n      // Check if aborted before backoff\n      failIfAborted(api.signal);\n      try {\n        await options.backoff(retry, options.maxRetries, api.signal);\n      } catch (backoffError) {\n        // If backoff was aborted, exit the retry loop\n        failIfAborted(api.signal);\n        // Otherwise, rethrow the backoff error\n        throw backoffError;\n      }\n    }\n  }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n  fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const INTERNAL_PREFIX = '__rtkq/';\nconst ONLINE = 'online';\nconst OFFLINE = 'offline';\nconst FOCUS = 'focus';\nconst FOCUSED = 'focused';\nconst VISIBILITYCHANGE = 'visibilitychange';\nexport const onFocus = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${FOCUSED}`);\nexport const onFocusLost = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);\nexport const onOnline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${ONLINE}`);\nexport const onOffline = /* @__PURE__ */createAction(`${INTERNAL_PREFIX}${OFFLINE}`);\nconst actions = {\n  onFocus,\n  onFocusLost,\n  onOnline,\n  onOffline\n};\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n}) => () => void) {\n  function defaultHandler() {\n    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map(action => () => dispatch(action()));\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus();\n      } else {\n        handleFocusLost();\n      }\n    };\n    let unsubscribe = () => {\n      initialized = false;\n    };\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        const handlers = {\n          [FOCUS]: handleFocus,\n          [VISIBILITYCHANGE]: handleVisibilityChange,\n          [ONLINE]: handleOnline,\n          [OFFLINE]: handleOffline\n        };\n        function updateListeners(add: boolean) {\n          Object.entries(handlers).forEach(([event, handler]) => {\n            if (add) {\n              window.addEventListener(event, handler, false);\n            } else {\n              window.removeEventListener(event, handler);\n            }\n          });\n        }\n        // Handle focus events\n        updateListeners(true);\n        initialized = true;\n        unsubscribe = () => {\n          updateListeners(false);\n          initialized = false;\n        };\n      }\n    }\n    return unsubscribe;\n  }\n  return customHandler ? customHandler(dispatch, actions) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nimport type { NamedSchemaError } from './standardSchema';\nimport { filterMap } from './utils/filterMap';\nconst rawResultType = /* @__PURE__ */Symbol();\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\nexport interface SchemaFailureInfo {\n  endpoint: string;\n  arg: any;\n  type: 'query' | 'mutation';\n  queryCacheKey?: string;\n}\nexport type SchemaFailureHandler = (error: NamedSchemaError, info: SchemaFailureInfo) => void;\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (error: NamedSchemaError, info: SchemaFailureInfo) => BaseQueryError<BaseQuery>;\nexport type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType extends BaseQueryResult<BaseQuery>> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *      // highlight-start\n   *      query: (body) => ({\n   *        url: `posts`,\n   *        method: 'POST',\n   *        body,\n   *      }),\n   *      // highlight-end\n   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *    }),\n   *   })\n   * })\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n  queryFn?: never;\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(baseQueryReturnValue: RawResultType, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import {customBaseQuery, baseQueryErrorSchema} from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n};\nexport type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random()\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' }\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' }\n   *         }\n   *         return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n   *       }\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n  query?: never;\n  transformResponse?: never;\n  transformErrorResponse?: never;\n  rawResponseSchema?: never;\n  rawErrorResponseSchema?: never;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType, RawResultType> = {\n  QueryArg: QueryArg;\n  BaseQuery: BaseQuery;\n  ResultType: ResultType;\n  RawResultType: RawResultType;\n};\nexport type SchemaType = 'arg' | 'rawResponse' | 'response' | 'rawErrorResponse' | 'errorResponse' | 'meta';\ninterface CommonEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>;\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() })\n   * type Post = v.InferOutput<typeof postSchema>\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>;\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryErrorSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>;\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   * import { customBaseQuery, baseQueryMetaSchema } from \"./customBaseQuery\"\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>;\n\n  /**\n   * Defaults to `true`.\n   *\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info)\n   *       },\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: \"CUSTOM_ERROR\",\n   *         error: error.schemaName + \" failed validation\",\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport 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> & {\n  /* phantom type */\n  [rawResultType]?: RawResultType;\n  /* phantom type */\n  [resultType]?: ResultType;\n  /* phantom type */\n  [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n  extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\nexport const ENDPOINT_QUERY = DefinitionType.query;\nexport const ENDPOINT_MUTATION = DefinitionType.mutation;\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery;\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => TagDescriptionArray<TagTypes>;\nexport type FullTagDescription<TagType> = {\n  type: TagType;\n  id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = TagDescriptionArray<TagTypes> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query;\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     })\n   *   })\n   * })\n   * ```\n   */\n  providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n    arg: QueryArg;\n    baseQueryMeta: BaseQueryMeta<BaseQuery>;\n    requestId: string;\n    fulfilledTimeStamp: number;\n  }): ResultType | void;\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    listItems: build.query<string[], number>({\n   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *     // Only have one cache entry because the arg always maps to one string\n   *     serializeQueryArgs: ({ endpointName }) => {\n   *       return endpointName\n   *      },\n   *      // Always merge incoming data to the cache entry\n   *      merge: (currentCache, newItems) => {\n   *        currentCache.push(...newItems)\n   *      },\n   *      // Refetch when the page arg changes\n   *      forceRefetch({ currentArg, previousArg }) {\n   *        return currentArg !== previousArg\n   *      },\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined;\n    previousArg: QueryArg | undefined;\n    state: RootState<any, any, string>;\n    endpointState?: QuerySubState<any>;\n  }): boolean;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery;\n  providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never;\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   * \n   * @example\n   * \n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * \n   * type Pokemon = {\n   *   id: string\n   *   name: string\n   * }\n   * \n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined\n   *         },\n   *       },\n   *       query({pageParam}) {\n   *         return `https://example.com/listItems?page=${pageParam}`\n   *       },\n   *     }),\n   *   }),\n   * })\n   \n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam, QueryArg>;\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>\n   * }\n   *\n   * createApi({\n   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *  endpoints: (build) => ({\n   *    // Example: an endpoint with an API client passed in as an argument,\n   *    // but only the item ID should be used as the cache key\n   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *      queryFn: async ({ id, client }) => {\n   *        const post = await client.fetchPost(id)\n   *        return { data: post }\n   *      },\n   *      // highlight-start\n   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *        const { id } = queryArgs\n   *        // This can return a string, an object, a number, or a boolean.\n   *        // If it returns an object, number or boolean, that value\n   *        // will be serialized automatically via `defaultSerializeQueryArgs`\n   *        return { id } // omit `client` from the cache key\n   *\n   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *        // return defaultSerializeQueryArgs({\n   *        //   endpointName,\n   *        //   queryArgs: { id },\n   *        //   endpointDefinition\n   *        // })\n   *        // Or  create and return a string yourself:\n   *        // return `getPost(${id})`\n   *      },\n   *      // highlight-end\n   *    }),\n   *  }),\n   *})\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType, RawResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath, RawResultType>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n  TagTypes: TagTypes;\n  ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n  type: DefinitionType.mutation;\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         }\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never;\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n}\nexport 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>;\nexport 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>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY;\n}\nexport function isAnyQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e);\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * const api = createApi({\n   *  baseQuery,\n   *  endpoints: (build) => ({\n   *    getPost: build.query({\n   *      query: (id) => ({ url: `post/${id}` }),\n   *      // Pick out data and prevent nested properties in a hook or selector\n   *      transformResponse: (response) => response.data,\n   *      // Pick out error and prevent nested properties in a hook or selector\n   *      transformErrorResponse: (response) => response.error,\n   *      // `result` is the server response\n   *      providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n   *    }),\n   *  }),\n   *});\n   *```\n   */\n  query<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```js\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * const api = createApi({\n   *   baseQuery,\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation({\n   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.error,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n   *      // trigger side effects or optimistic updates\n   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n   *      // handle subscriptions etc\n   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<ResultType, QueryArg, RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath, RawResultType>;\n  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>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description) ? description(result as ResultType, error as undefined, queryArg, meta as MetaType) : description;\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, tag => assertTagTypes(expandTagDescription(tag)));\n  }\n  return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n  return typeof description === 'string' ? {\n    type: description\n  } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any> ? QA : never;\nexport 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;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown;\nexport 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;\nexport 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;\nexport 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;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg;\n  pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","export { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from 'immer';","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { ENDPOINT_QUERY, isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { filterNullishValues } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n  initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n  initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n  [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\ntype RefetchOptions = {\n  refetchCachedPages?: boolean;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection;\n  param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>, InfiniteQueryArgFrom<D>>>, 'initialPageParam' | 'refetchCachedPages'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n  requestId: string;\n  subscriptionOptions: SubscriptionOptions | undefined;\n  abort(): void;\n  unsubscribe(): void;\n  updateSubscriptionOptions(options: SubscriptionOptions): void;\n  queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n  arg: any;\n  unwrap(): Promise<any>;\n  refetch(options?: RefetchOptions): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: QueryArgFrom<D>;\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n  arg: InfiniteQueryArgFrom<D>;\n  unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n  refetch(options?: Pick<StartInfiniteQueryActionCreatorOptions<D>, 'refetchCachedPages'>): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n  fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n  data: ResultTypeFrom<D>;\n  error?: undefined;\n} | {\n  data?: undefined;\n  error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string;\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>;\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean;\n    fixedCacheKey?: string;\n  };\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string;\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void;\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>;\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void;\n};\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context,\n  getInternalState\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  api: Api<any, EndpointDefinitions, any, any>;\n  context: ApiContext<EndpointDefinitions>;\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState;\n}) {\n  const getRunningQueries = (dispatch: Dispatch) => getInternalState(dispatch)?.runningQueries;\n  const getRunningMutations = (dispatch: Dispatch) => getInternalState(dispatch)?.runningMutations;\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions\n  } = api.internalActions;\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk\n  };\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      return getRunningQueries(dispatch)?.get(queryCacheKey) as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningMutationThunk(\n  /**\n   * this is only here to allow TS to infer the result type by input value\n   * we could use it to validate the result, but it's probably not necessary\n   */\n  _endpointName: string, fixedCacheKeyOrRequestId: string) {\n    return (dispatch: Dispatch) => {\n      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as MutationActionCreatorResult<never> | undefined;\n    };\n  }\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningQueries(dispatch));\n  }\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) => filterNullishValues(getRunningMutations(dispatch));\n  }\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return;\n      const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n      (middlewareWarning as any).triggered = true;\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n        // Otherwise, must not have been added\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n      }\n    }\n  }\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n    const queryAction: AnyQueryActionCreator<any> = (arg, {\n      subscribe = true,\n      forceRefetch,\n      subscriptionOptions,\n      [forceQueryFnSymbol]: forceQueryFn,\n      ...rest\n    } = {}) => (dispatch, getState) => {\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName\n      });\n      let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n      const commonThunkArgs = {\n        ...rest,\n        type: ENDPOINT_QUERY as 'query',\n        subscribe,\n        forceRefetch: forceRefetch,\n        subscriptionOptions,\n        endpointName,\n        originalArgs: arg,\n        queryCacheKey,\n        [forceQueryFnSymbol]: forceQueryFn\n      };\n      if (isQueryDefinition(endpointDefinition)) {\n        thunk = queryThunk(commonThunkArgs);\n      } else {\n        const {\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam' | 'refetchCachedPages'>;\n        thunk = infiniteQueryThunk({\n          ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n          // Supply these even if undefined. This helps with a field existence\n          // check over in `buildSlice.ts`\n          direction,\n          initialPageParam,\n          refetchCachedPages\n        });\n      }\n      const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n      const thunkResult = dispatch(thunk);\n      const stateAfter = selector(getState());\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort\n      } = thunkResult;\n      const skippedSynchronously = stateAfter.requestId !== requestId;\n      const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);\n      const selectFromState = () => selector(getState());\n      const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n      // a query has been forced (upsertQueryData)\n      // -> we want to resolve it once data has been written with the data that will be written\n      thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n      // a query has been skipped due to a condition and we do not have any currently running query\n      // -> we want to resolve it immediately with the current data\n      Promise.resolve(stateAfter) :\n      // query just started or one is already in flight\n      // -> wait for the running query, then resolve with data from after that\n      Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n        arg,\n        requestId,\n        subscriptionOptions,\n        queryCacheKey,\n        abort,\n        async unwrap() {\n          const result = await statePromise;\n          if (result.isError) {\n            throw result.error;\n          }\n          return result.data;\n        },\n        refetch: (options?: RefetchOptions) => dispatch(queryAction(arg, {\n          subscribe: false,\n          forceRefetch: true,\n          ...options\n        })),\n        unsubscribe() {\n          if (subscribe) dispatch(unsubscribeQueryResult({\n            queryCacheKey,\n            requestId\n          }));\n        },\n        updateSubscriptionOptions(options: SubscriptionOptions) {\n          statePromise.subscriptionOptions = options;\n          dispatch(updateSubscriptionOptions({\n            endpointName,\n            requestId,\n            queryCacheKey,\n            options\n          }));\n        }\n      });\n      if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n        const runningQueries = getRunningQueries(dispatch)!;\n        runningQueries.set(queryCacheKey, statePromise);\n        statePromise.then(() => {\n          runningQueries.delete(queryCacheKey);\n        });\n      }\n      return statePromise;\n    };\n    return queryAction;\n  }\n  function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return queryAction;\n  }\n  function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n    return infiniteQueryAction;\n  }\n  function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n    return (arg, {\n      track = true,\n      fixedCacheKey\n    } = {}) => (dispatch, getState) => {\n      const thunk = mutationThunk({\n        type: 'mutation',\n        endpointName,\n        originalArgs: arg,\n        track,\n        fixedCacheKey\n      });\n      const thunkResult = dispatch(thunk);\n      middlewareWarning(dispatch);\n      const {\n        requestId,\n        abort,\n        unwrap\n      } = thunkResult;\n      const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n        data\n      })), error => ({\n        error\n      }));\n      const reset = () => {\n        dispatch(removeMutationResult({\n          requestId,\n          fixedCacheKey\n        }));\n      };\n      const ret = Object.assign(returnValuePromise, {\n        arg: thunkResult.arg,\n        requestId,\n        abort,\n        unwrap,\n        reset\n      });\n      const runningMutations = getRunningMutations(dispatch)!;\n      runningMutations.set(requestId, ret);\n      ret.then(() => {\n        runningMutations.delete(requestId);\n      });\n      if (fixedCacheKey) {\n        runningMutations.set(fixedCacheKey, ret);\n        ret.then(() => {\n          if (runningMutations.get(fixedCacheKey) === ret) {\n            runningMutations.delete(fixedCacheKey);\n          }\n        });\n      }\n      return ret;\n    };\n  }\n}","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn } from './baseQueryTypes';\nimport type { CombinedState, CoreModule, QueryKeys } from './core';\nimport type { ApiModules } from './core/module';\nimport type { CreateApiOptions } from './createApi';\nimport type { EndpointBuilder, EndpointDefinition, EndpointDefinitions, UpdateDefinitions } from './endpointDefinitions';\nimport type { NoInfer, UnionToIntersection, WithRequiredProp } from './tsHelpers';\nexport type ModuleName = keyof ApiModules<any, any, any, any>;\nexport type Module<Name extends ModuleName> = {\n  name: Name;\n  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>): {\n    injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;\n  };\n};\nexport interface ApiContext<Definitions extends EndpointDefinitions> {\n  apiUid: string;\n  endpointDefinitions: Definitions;\n  batch(cb: () => void): void;\n  extractRehydrationInfo: (action: UnknownAction) => CombinedState<any, any, any> | undefined;\n  hasRehydrationInfo: (action: UnknownAction) => boolean;\n}\nexport const getEndpointDefinition = <Definitions extends EndpointDefinitions, EndpointName extends keyof Definitions>(context: ApiContext<Definitions>, endpointName: EndpointName) => context.endpointDefinitions[endpointName];\nexport 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]> & {\n  /**\n   * 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.\n   */\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\n    endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;\n    /**\n     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n     *\n     * If set to `true`, will override existing endpoints with the new definition.\n     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n     */\n    overrideExisting?: boolean | 'throw';\n  }): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;\n  /**\n   *A function to enhance a generated API with additional information. Useful with code-generation.\n   */\n  enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {\n    addTagTypes?: readonly NewTagTypes[];\n    endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? { [K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void) } : never;\n  }): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;\n};","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { SchemaError } from '@standard-schema/utils';\nimport type { SchemaType } from './endpointDefinitions';\nexport class NamedSchemaError extends SchemaError {\n  constructor(issues: readonly StandardSchemaV1.Issue[], public readonly value: any, public readonly schemaName: `${SchemaType}Schema`, public readonly _bqMeta: any) {\n    super(issues);\n  }\n}\nexport const shouldSkip = (skipSchemaValidation: boolean | SchemaType[] | undefined, schemaName: SchemaType) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(schema: Schema, data: unknown, schemaName: `${SchemaType}Schema`, bqMeta: any): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data);\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);\n  }\n  return result.value;\n}","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from '../utils/immerImports';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultDescription, ResultTypeFrom, SchemaFailureConverter, SchemaFailureHandler, SchemaFailureInfo, SchemaType } from '../endpointDefinitions';\nimport { calculateProvidedBy, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nimport { parseWithSchema, NamedSchemaError, shouldSkip } from '../standardSchema';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : 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 & {\n  originalArgs: QueryArg;\n}, ATConfig & {\n  rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>;\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n  type: 'query';\n  originalArgs: unknown;\n  endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n  type: `query`;\n  originalArgs: unknown;\n  endpointName: string;\n  param: unknown;\n  direction?: InfiniteQueryDirection;\n  refetchCachedPages?: boolean;\n};\ntype MutationThunkArg = {\n  type: 'mutation';\n  originalArgs: unknown;\n  endpointName: string;\n  track?: boolean;\n  fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n  pendingMeta: {\n    startedTimeStamp: number;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  fulfilledMeta: {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n  rejectedMeta: {\n    baseQueryMeta: unknown;\n    [SHOULD_AUTOBATCH]: true;\n  };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;\nexport type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;\nexport type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;\nexport type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;\nexport type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[];\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[];\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n  [SHOULD_AUTOBATCH]: true;\n} => {\n  return {\n    ...arg,\n    [SHOULD_AUTOBATCH]: true\n  };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n  reducerPath,\n  baseQuery,\n  context: {\n    endpointDefinitions\n  },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation\n}: {\n  baseQuery: BaseQuery;\n  reducerPath: ReducerPath;\n  context: ApiContext<Definitions>;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  api: Api<BaseQuery, Definitions, ReducerPath, any>;\n  assertTagType: AssertTagTypes;\n  selectors: AllSelectors;\n  onSchemaFailure: SchemaFailureHandler | undefined;\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined;\n  skipSchemaValidation: boolean | SchemaType[] | undefined;\n}) {\n  type State = RootState<any, string, ReducerPath>;\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n    const endpointDefinition = endpointDefinitions[endpointName];\n    const queryCacheKey = serializeQueryArgs({\n      queryArgs: arg,\n      endpointDefinition,\n      endpointName\n    });\n    dispatch(api.internalActions.queryResultPatched({\n      queryCacheKey,\n      patches\n    }));\n    if (!updateProvided) {\n      return;\n    }\n    const newValue = api.endpoints[endpointName].select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n    dispatch(api.internalActions.updateProvidedBy([{\n      queryCacheKey,\n      providedTags\n    }]));\n  };\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items];\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n  }\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item];\n    return max && newItems.length > max ? newItems.slice(1) : newItems;\n  }\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n    const endpointDefinition = api.endpoints[endpointName];\n    const currentState = endpointDefinition.select(arg)(\n    // Work around TS 4.1 mismatch\n    getState() as RootState<any, any, any>);\n    const ret: PatchCollection = {\n      patches: [],\n      inversePatches: [],\n      undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n    };\n    if (currentState.status === STATUS_UNINITIALIZED) {\n      return ret;\n    }\n    let newValue;\n    if ('data' in currentState) {\n      if (isDraftable(currentState.data)) {\n        const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n        ret.patches.push(...patches);\n        ret.inversePatches.push(...inversePatches);\n        newValue = value;\n      } else {\n        newValue = updateRecipe(currentState.data);\n        ret.patches.push({\n          op: 'replace',\n          path: [],\n          value: newValue\n        });\n        ret.inversePatches.push({\n          op: 'replace',\n          path: [],\n          value: currentState.data\n        });\n      }\n    }\n    if (ret.patches.length === 0) {\n      return ret;\n    }\n    dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n    return ret;\n  };\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n    type EndpointName = typeof endpointName;\n    const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n      subscribe: false,\n      forceRefetch: true,\n      [forceQueryFnSymbol]: () => ({\n        data: value\n      })\n    })) as UpsertThunkResult<Definitions, EndpointName>;\n    return res;\n  };\n  const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n  };\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }> = async (arg, {\n    signal,\n    abort,\n    rejectWithValue,\n    fulfillWithValue,\n    dispatch,\n    getState,\n    extra\n  }) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName];\n    const {\n      metaSchema,\n      skipSchemaValidation = globalSkipSchemaValidation\n    } = endpointDefinition;\n    const isQuery = arg.type === ENDPOINT_QUERY;\n    try {\n      let transformResponse: TransformCallback = defaultTransformResponse;\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n      };\n      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined;\n      let finalQueryReturnValue: QueryReturnValue;\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({\n            data\n          });\n        }\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param\n        };\n        const pageResponse = await executeRequest(finalQueryArg);\n        const addTo = previous ? addToStart : addToEnd;\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages)\n          },\n          meta: pageResponse.meta\n        };\n      };\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n        let result: QueryReturnValue;\n        const {\n          extraOptions,\n          argSchema,\n          rawResponseSchema,\n          responseSchema\n        } = endpointDefinition;\n        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {\n          finalQueryArg = await parseWithSchema(argSchema, finalQueryArg, 'argSchema', {} // we don't have a meta yet, so we can't pass it\n          );\n        }\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn();\n        } else if (endpointDefinition.query) {\n          // We should only run `transformResponse` when the endpoint has a `query` method,\n          // and we're not doing an `upsertQueryData`.\n          transformResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n          result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n        } else {\n          result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n          let err: undefined | string;\n          if (!result) {\n            err = `${what} did not return anything.`;\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`;\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`;\n                break;\n              }\n            }\n          }\n          if (err) {\n            console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`, result);\n          }\n        }\n        if (result.error) throw new HandledError(result.error, result.meta);\n        let {\n          data\n        } = result;\n        if (rawResponseSchema && !shouldSkip(skipSchemaValidation, 'rawResponse')) {\n          data = await parseWithSchema(rawResponseSchema, result.data, 'rawResponseSchema', result.meta);\n        }\n        let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);\n        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {\n          transformedResponse = await parseWithSchema(responseSchema, transformedResponse, 'responseSchema', result.meta);\n        }\n        return {\n          ...result,\n          data: transformedResponse\n        };\n      }\n      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const {\n          infiniteQueryOptions\n        } = endpointDefinition;\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const {\n          maxPages = Infinity\n        } = infiniteQueryOptions;\n\n        // Priority: per-call override > endpoint config > default (true)\n        const refetchCachedPages = (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;\n        let result: QueryReturnValue;\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = {\n          pages: [],\n          pageParams: []\n        };\n        const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch =\n        // arg.forceRefetch\n        isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n        const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward';\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n          const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);\n          result = await fetchPage(existingData, param, maxPages, previous);\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const {\n            initialPageParam = infiniteQueryOptions.initialPageParam\n          } = arg as InfiniteQueryThunkArg<any>;\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? [];\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n          const totalPages = cachedPageParams.length;\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages);\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n            } as QueryReturnValue;\n          }\n          if (refetchCachedPages) {\n            // Fetch remaining pages\n            for (let i = 1; i < totalPages; i++) {\n              const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>, arg.originalArgs);\n              result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n            }\n          }\n        }\n        finalQueryReturnValue = result;\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs);\n      }\n      if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta') && finalQueryReturnValue.meta) {\n        finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, 'metaSchema', finalQueryReturnValue.meta);\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n        fulfilledTimeStamp: Date.now(),\n        baseQueryMeta: finalQueryReturnValue.meta\n      }));\n    } catch (error) {\n      let caughtError = error;\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n        const {\n          rawErrorResponseSchema,\n          errorResponseSchema\n        } = endpointDefinition;\n        let {\n          value,\n          meta\n        } = caughtError;\n        try {\n          if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, 'rawErrorResponse')) {\n            value = await parseWithSchema(rawErrorResponseSchema, value, 'rawErrorResponseSchema', meta);\n          }\n          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta);\n          }\n          let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);\n          if (errorResponseSchema && !shouldSkip(skipSchemaValidation, 'errorResponse')) {\n            transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, 'errorResponseSchema', meta);\n          }\n          return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({\n            baseQueryMeta: meta\n          }));\n        } catch (e) {\n          caughtError = e;\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: isQuery ? arg.queryCacheKey : undefined\n          };\n          endpointDefinition.onSchemaFailure?.(caughtError, info);\n          onSchemaFailure?.(caughtError, info);\n          const {\n            catchSchemaFailure = globalCatchSchemaFailure\n          } = endpointDefinition;\n          if (catchSchemaFailure) {\n            return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({\n              baseQueryMeta: caughtError._bqMeta\n            }));\n          }\n        }\n      } catch (e) {\n        caughtError = e;\n      }\n      if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n        console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, caughtError);\n      } else {\n        console.error(caughtError);\n      }\n      throw caughtError;\n    }\n  };\n  function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n    const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n    const fulfilledVal = requestState?.fulfilledTimeStamp;\n    const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n    }\n    return false;\n  }\n  const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n    const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n      state: RootState<any, string, ReducerPath>;\n    }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({\n        arg\n      }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName];\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n            direction: (arg as InfiniteQueryThunkArg<any>).direction\n          } : {})\n        });\n      },\n      condition(queryThunkArg, {\n        getState\n      }) {\n        const state = getState();\n        const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n        const fulfilledVal = requestState?.fulfilledTimeStamp;\n        const currentArg = queryThunkArg.originalArgs;\n        const previousArg = requestState?.originalArgs;\n        const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true;\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false;\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true;\n        }\n        if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n          currentArg,\n          previousArg,\n          endpointState: requestState,\n          state\n        })) {\n          return true;\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false;\n        }\n        return true;\n      },\n      dispatchConditionRejection: true\n    });\n    return generatedQueryThunk;\n  };\n  const queryThunk = createQueryThunk<QueryThunkArg>();\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n  const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n    state: RootState<any, string, ReducerPath>;\n  }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({\n        startedTimeStamp: Date.now()\n      });\n    }\n  });\n  const hasTheForce = (options: any): options is {\n    force: boolean;\n  } => 'force' in options;\n  const hasMaxAge = (options: any): options is {\n    ifOlderThan: false | number;\n  } => 'ifOlderThan' in options;\n  const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions = {}): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n    const force = hasTheForce(options) && options.force;\n    const maxAge = hasMaxAge(options) && options.ifOlderThan;\n    const queryAction = (force: boolean = true) => {\n      const options: StartQueryActionCreatorOptions = {\n        forceRefetch: force,\n        subscribe: false\n      };\n      return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n    };\n    const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n    if (force) {\n      dispatch(queryAction());\n    } else if (maxAge) {\n      const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n      if (!lastFulfilledTs) {\n        dispatch(queryAction());\n        return;\n      }\n      const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n      if (shouldRetrigger) {\n        dispatch(queryAction());\n      }\n    } else {\n      // If prefetching with no options, just let it try\n      dispatch(queryAction(false));\n    }\n  };\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n  }\n  function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n    } as Matchers<Thunk, any>;\n  }\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions\n  };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  const lastIndex = pages.length - 1;\n  return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown, unknown>, {\n  pages,\n  pageParams\n}: InfiniteData<unknown, unknown>, queryArg: unknown): unknown | undefined {\n  return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n  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);\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../utils/immerImports';\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}","import type { PayloadAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { STATUS_FULFILLED, STATUS_PENDING, QueryStatus, STATUS_REJECTED, STATUS_UNINITIALIZED } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { ENDPOINT_QUERY, isInfiniteQueryDefinition, type AssertTagTypes, type EndpointDefinitions, type FullTagDescription, type QueryDefinition } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { applyPatches, original, isDraft } from '../utils/immerImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport { getCurrent } from '../utils/getCurrent';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n  endpointName: EndpointName;\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string;\n  arg: unknown;\n  value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg;\n  value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n  const substate = state[queryCacheKey];\n  if (substate) {\n    update(substate);\n  }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string;\n  requestId?: string;\n} | MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n  requestId: string;\n  arg: {\n    fixedCacheKey?: string | undefined;\n  };\n}, update: (substate: MutationSubState<any>) => void) {\n  const substate = state[getMutationCacheKey(id)];\n  if (substate) {\n    update(substate);\n  }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo\n  },\n  assertTagType,\n  config\n}: {\n  reducerPath: string;\n  queryThunk: QueryThunk;\n  infiniteQueryThunk: InfiniteQueryThunk<any>;\n  mutationThunk: MutationThunk;\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  context: ApiContext<EndpointDefinitions>;\n  assertTagType: AssertTagTypes;\n  config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`);\n  function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n    // requestStatus: 'pending'\n  } & {\n    startedTimeStamp: number;\n  }) {\n    draft[arg.queryCacheKey] ??= {\n      status: STATUS_UNINITIALIZED,\n      endpointName: arg.endpointName\n    };\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n      substate.status = STATUS_PENDING;\n      substate.requestId = upserting && substate.requestId ?\n      // for `upsertQuery` **updates**, keep the current `requestId`\n      substate.requestId :\n      // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n      meta.requestId;\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs;\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp;\n      const endpointDefinition = definitions[meta.arg.endpointName];\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;\n        (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n      }\n    });\n  }\n  function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n    arg: QueryThunkArg;\n    requestId: string;\n  } & {\n    fulfilledTimeStamp: number;\n    baseQueryMeta: unknown;\n  }, payload: unknown, upserting: boolean) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n      if (substate.requestId !== meta.requestId && !upserting) return;\n      const {\n        merge\n      } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n      substate.status = STATUS_FULFILLED;\n      if (merge) {\n        if (substate.data !== undefined) {\n          const {\n            fulfilledTimeStamp,\n            arg,\n            baseQueryMeta,\n            requestId\n          } = meta;\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, draftSubstateData => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId\n            });\n          });\n          substate.data = newData;\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload;\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n      }\n      delete substate.error;\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n    });\n  }\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey\n          }\n        }: PayloadAction<QuerySubstateIdentifier>) {\n          delete draft[queryCacheKey];\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n      },\n      cacheEntriesUpserted: {\n        reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n          RTK_autoBatch: boolean;\n          requestId: string;\n          timestamp: number;\n        }>) {\n          for (const entry of action.payload) {\n            const {\n              queryDescription: arg,\n              value\n            } = entry;\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp\n            });\n            writeFulfilledCacheEntry(draft, {\n              arg,\n              requestId: action.meta.requestId,\n              fulfilledTimeStamp: action.meta.timestamp,\n              baseQueryMeta: {}\n            }, value,\n            // We know we're upserting here\n            true);\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n            const {\n              endpointName,\n              arg,\n              value\n            } = entry;\n            const endpointDefinition = definitions[endpointName];\n            const queryDescription: QueryThunkArg = {\n              type: ENDPOINT_QUERY as 'query',\n              endpointName,\n              originalArgs: entry.arg,\n              queryCacheKey: serializeQueryArgs({\n                queryArgs: arg,\n                endpointDefinition,\n                endpointName\n              })\n            };\n            return {\n              queryDescription,\n              value\n            };\n          });\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now()\n            }\n          };\n          return result;\n        }\n      },\n      queryResultPatched: {\n        reducer(draft, {\n          payload: {\n            queryCacheKey,\n            patches\n          }\n        }: PayloadAction<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n            substate.data = applyPatches(substate.data as any, patches.concat());\n          });\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n          patches: readonly Patch[];\n        }>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(queryThunk.pending, (draft, {\n        meta,\n        meta: {\n          arg\n        }\n      }) => {\n        const upserting = isUpsertQuery(arg);\n        writePendingCacheEntry(draft, arg, upserting, meta);\n      }).addCase(queryThunk.fulfilled, (draft, {\n        meta,\n        payload\n      }) => {\n        const upserting = isUpsertQuery(meta.arg);\n        writeFulfilledCacheEntry(draft, meta, payload, upserting);\n      }).addCase(queryThunk.rejected, (draft, {\n        meta: {\n          condition,\n          arg,\n          requestId\n        },\n        error,\n        payload\n      }) => {\n        updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n          if (condition) {\n            // request was aborted due to condition (another query already running)\n          } else {\n            // request failed\n            if (substate.requestId !== requestId) return;\n            substate.status = STATUS_REJECTED;\n            substate.error = (payload ?? error) as any;\n          }\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          queries\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(queries)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, {\n          payload\n        }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload);\n          if (cacheKey in draft) {\n            delete draft[cacheKey];\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(mutationThunk.pending, (draft, {\n        meta,\n        meta: {\n          requestId,\n          arg,\n          startedTimeStamp\n        }\n      }) => {\n        if (!arg.track) return;\n        draft[getMutationCacheKey(meta)] = {\n          requestId,\n          status: STATUS_PENDING,\n          endpointName: arg.endpointName,\n          startedTimeStamp\n        };\n      }).addCase(mutationThunk.fulfilled, (draft, {\n        payload,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_FULFILLED;\n          substate.data = payload;\n          substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n        });\n      }).addCase(mutationThunk.rejected, (draft, {\n        payload,\n        error,\n        meta\n      }) => {\n        if (!meta.arg.track) return;\n        updateMutationSubstateIfExists(draft, meta, substate => {\n          if (substate.requestId !== meta.requestId) return;\n          substate.status = STATUS_REJECTED;\n          substate.error = (payload ?? error) as any;\n        });\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          mutations\n        } = extractRehydrationInfo(action)!;\n        for (const [key, entry] of Object.entries(mutations)) {\n          if (\n          // do not rehydrate entries that were currently in flight.\n          (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) &&\n          // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n          key !== entry?.requestId) {\n            draft[key] = entry;\n          }\n        }\n      });\n    }\n  });\n  type CalculateProvidedByAction = UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<InfiniteQueryThunk<any>>>>;\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {}\n  };\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(draft, action: PayloadAction<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>) {\n          for (const {\n            queryCacheKey,\n            providedTags\n          } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey);\n            for (const {\n              type,\n              id\n            } of providedTags) {\n              const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] = providedTags as FullTagDescription<string>[];\n          }\n        },\n        prepare: prepareAutoBatched<Array<{\n          queryCacheKey: QueryCacheKey;\n          providedTags: readonly FullTagDescription<string>[];\n        }>>()\n      }\n    },\n    extraReducers(builder) {\n      builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n        payload: {\n          queryCacheKey\n        }\n      }) => {\n        removeCacheKeyFromTags(draft, queryCacheKey);\n      }).addMatcher(hasRehydrationInfo, (draft, action) => {\n        const {\n          provided\n        } = extractRehydrationInfo(action)!;\n        for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {\n          for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n            const subscribedQueries = (draft.tags[type] ??= {})[id || '__internal_without_id'] ??= [];\n            for (const queryCacheKey of cacheKeys) {\n              const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey);\n              }\n              draft.keys[queryCacheKey] = provided.keys[queryCacheKey];\n            }\n          }\n        }\n      }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n        writeProvidedTagsForQueries(draft, [action]);\n      }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {\n        const mockActions: CalculateProvidedByAction[] = action.payload.map(({\n          queryDescription,\n          value\n        }) => {\n          return {\n            type: 'UNKNOWN',\n            payload: value,\n            meta: {\n              requestStatus: 'fulfilled',\n              requestId: 'UNKNOWN',\n              arg: queryDescription\n            }\n          };\n        });\n        writeProvidedTagsForQueries(draft, mockActions);\n      });\n    }\n  });\n  function removeCacheKeyFromTags(draft: InvalidationState<any>, queryCacheKey: QueryCacheKey) {\n    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type;\n      const tagId = tag.id ?? '__internal_without_id';\n      const tagSubscriptions = draft.tags[tagType]?.[tagId];\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(qc => qc !== queryCacheKey);\n      }\n    }\n    delete draft.keys[queryCacheKey];\n  }\n  function writeProvidedTagsForQueries(draft: InvalidationState<string>, actions: CalculateProvidedByAction[]) {\n    const providedByEntries = actions.map(action => {\n      const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n      const {\n        queryCacheKey\n      } = action.meta.arg;\n      return {\n        queryCacheKey,\n        providedTags\n      };\n    });\n    invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(d, a: PayloadAction<{\n        endpointName: string;\n        requestId: string;\n        options: Subscribers[number];\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      unsubscribeQueryResult(d, a: PayloadAction<{\n        requestId: string;\n      } & QuerySubstateIdentifier>) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {}\n    }\n  });\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload);\n        },\n        prepare: prepareAutoBatched<Patch[]>()\n      }\n    }\n  });\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, {\n        payload\n      }: PayloadAction<string>) {\n        state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n      }\n    },\n    extraReducers: builder => {\n      builder.addCase(onOnline, state => {\n        state.online = true;\n      }).addCase(onOffline, state => {\n        state.online = false;\n      }).addCase(onFocus, state => {\n        state.focused = true;\n      }).addCase(onFocusLost, state => {\n        state.focused = false;\n      })\n      // update the state to be a new object to be picked up as a \"state change\"\n      // by redux-persist's `autoMergeLevel2`\n      .addMatcher(hasRehydrationInfo, draft => ({\n        ...draft\n      }));\n    }\n  });\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer\n  });\n  const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState\n  };\n  return {\n    reducer,\n    actions\n  };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { filterMap, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState, QueryStatus } from './apiState';\nimport { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { type AllQueryKeys, getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n  select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean;\n  hasPreviousPage: boolean;\n  isFetchingNextPage: boolean;\n  isFetchingPreviousPage: boolean;\n  isFetchNextPageError: boolean;\n  isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n  requestId: string | undefined;\n  fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n  status: STATUS_UNINITIALIZED\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs;\n  reducerPath: ReducerPath;\n  createSelector: typeof _createSelector;\n}) {\n  type RootState = _RootState<Definitions, string, string>;\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig\n  };\n  function withRequestFlags<T extends {\n    status: QueryStatus;\n  }>(substate: T): T & RequestStatusFlags {\n    return {\n      ...substate,\n      ...getRequestStatusFlags(substate.status)\n    };\n  }\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath];\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state;\n        (selectApiState as any).triggered = true;\n        console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n      }\n    }\n    return state;\n  }\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries;\n  }\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey];\n  }\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations;\n  }\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config;\n  }\n  function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n    status: QueryStatus;\n  }>(substate: T) => T & RequestStatusFlags) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner);\n      }\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName\n      });\n      const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n      return createSelector(selectQuerySubstate, combiner);\n    };\n  }\n  function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n  }\n  function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n    const {\n      infiniteQueryOptions\n    } = endpointDefinition;\n    function withInfiniteQueryResultFlags<T extends {\n      status: QueryStatus;\n    }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status)\n      };\n      const {\n        isLoading,\n        isError,\n        direction\n      } = stateWithRequestFlags;\n      const isForward = direction === 'forward';\n      const isBackward = direction === 'backward';\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward\n      };\n    }\n    return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n  }\n  function buildMutationSelector() {\n    return (id => {\n      let mutationId: string | typeof skipToken;\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken;\n      } else {\n        mutationId = id;\n      }\n      const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n      const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n      return createSelector(finalSelectMutationSubstate, withRequestFlags);\n    }) as MutationResultSelectorFactory<any, RootState>;\n  }\n  function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n    endpointName: string;\n    originalArgs: any;\n    queryCacheKey: QueryCacheKey;\n  }> {\n    const apiState = state[reducerPath];\n    const toInvalidate = new Set<QueryCacheKey>();\n    const finalTags = filterMap(tags, isNotNullish, expandTagDescription);\n    for (const tag of finalTags) {\n      const provided = apiState.provided.tags[tag.type];\n      if (!provided) {\n        continue;\n      }\n      let invalidateSubscriptions = (tag.id !== undefined ?\n      // id given: invalidate all queries that provide this type & id\n      provided[tag.id] :\n      // no id: invalidate all queries that provide this type\n      Object.values(provided).flat()) ?? [];\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate);\n      }\n    }\n    return Array.from(toInvalidate.values()).flatMap(queryCacheKey => {\n      const querySubState = apiState.queries[queryCacheKey];\n      return querySubState ? {\n        queryCacheKey,\n        endpointName: querySubState.endpointName!,\n        originalArgs: querySubState.originalArgs\n      } : [];\n    });\n  }\n  function selectCachedArgsForQuery<QueryName extends AllQueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return filterMap(Object.values(selectQueries(state) as QueryState<any>), (entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n      status: QueryStatus.uninitialized;\n    }> => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, entry => entry.originalArgs);\n  }\n  function getHasNextPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data) return false;\n    return getNextPageParam(options, data, queryArg) != null;\n  }\n  function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any, any>, data?: InfiniteData<unknown, unknown>, queryArg?: unknown): boolean {\n    if (!data || !options.getPreviousPageParam) return false;\n    return getPreviousPageParam(options, data, queryArg) != null;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport { getEndpointDefinition, type Api, type ApiContext, type Module, type ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions, SchemaFailureConverter, SchemaFailureHandler, SchemaType } from './endpointDefinitions';\nimport { DefinitionType, ENDPOINT_INFINITEQUERY, ENDPOINT_MUTATION, ENDPOINT_QUERY, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n  /**\n   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery;\n  /**\n   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[];\n  /**\n   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath;\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>;\n  /**\n   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n   */\n  endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n  /**\n   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts'\n   *     })\n   *   }),\n   *   // highlight-start\n   *   keepUnusedDataFor: 5\n   *   // highlight-end\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately';\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (action: UnknownAction, {\n    reducerPath\n  }: {\n    reducerPath: ReducerPath;\n  }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * 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).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler;\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>;\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[];\n}\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n      reducerPath: (options.reducerPath ?? 'api') as any\n    }));\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n          finalSerializeQueryArgs = queryArgsApi => {\n            const initialResult = endpointSQA(queryArgsApi);\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult;\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult\n              });\n            }\n          };\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs;\n        }\n        return finalSerializeQueryArgs(queryArgsApi);\n      },\n      tagTypes: [...(options.tagTypes || [])]\n    };\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn();\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n    };\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({\n        addTagTypes,\n        endpoints\n      }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;\n              (optionsWithDefaults.tagTypes as any[]).push(eT);\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(getEndpointDefinition(context, endpointName));\n            } else {\n              Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);\n            }\n          }\n        }\n        return api;\n      }\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n    const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n    function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: x => ({\n          ...x,\n          type: ENDPOINT_QUERY\n        }) as any,\n        mutation: x => ({\n          ...x,\n          type: ENDPOINT_MUTATION\n        }) as any,\n        infiniteQuery: x => ({\n          ...x,\n          type: ENDPOINT_INFINITEQUERY\n        }) as any\n      });\n      for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n        if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n            console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n          }\n          continue;\n        }\n        if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n          if (isInfiniteQueryDefinition(definition)) {\n            const {\n              infiniteQueryOptions\n            } = definition;\n            const {\n              maxPages,\n              getPreviousPageParam\n            } = infiniteQueryOptions;\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n              }\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n              }\n            }\n          }\n        }\n        context.endpointDefinitions[endpointName] = definition;\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition);\n        }\n      }\n      return api as any;\n    }\n    return api.injectEndpoints({\n      endpoints: options.endpoints as any\n    });\n  };\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs\n}) => {\n  let serialized = '';\n  const cached = cache?.get(queryArgs);\n  if (typeof cached === 'string') {\n    serialized = cached;\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? {\n        $bigint: value.toString()\n      } : value;\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n        acc[key] = (value as any)[key];\n        return acc;\n      }, {}) : value;\n      return value;\n    });\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified);\n    }\n    serialized = stringified;\n  }\n  return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any;\n  endpointDefinition: EndpointDefinition<any, any, any, any>;\n  endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n  return function () {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n  };\n}","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n  return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionInternalState, SubscriptionState } from '../apiState';\nimport { produceWithPatches } from '../../utils/immerImports';\nimport type { Action } from '@reduxjs/toolkit';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n  api,\n  queryThunk,\n  internalState,\n  mwApi\n}) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n  let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n  const {\n    updateSubscriptionOptions,\n    unsubscribeQueryResult\n  } = api.internalActions;\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (currentSubscriptions: SubscriptionInternalState, action: Action) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const {\n        queryCacheKey,\n        requestId,\n        options\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub?.has(requestId)) {\n        sub.set(requestId, options);\n      }\n      return true;\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const {\n        queryCacheKey,\n        requestId\n      } = action.payload;\n      const sub = currentSubscriptions.get(queryCacheKey);\n      if (sub) {\n        sub.delete(requestId);\n      }\n      return true;\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      currentSubscriptions.delete(action.payload.queryCacheKey);\n      return true;\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: {\n          arg,\n          requestId\n        }\n      } = action;\n      const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n      if (arg.subscribe) {\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n      }\n      return true;\n    }\n    let mutated = false;\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: {\n          condition,\n          arg,\n          requestId\n        }\n      } = action;\n      if (condition && arg.subscribe) {\n        const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);\n        substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});\n        mutated = true;\n      }\n    }\n    return mutated;\n  };\n  const getSubscriptions = () => internalState.currentSubscriptions;\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions();\n    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);\n    return subscriptionsForQueryArg?.size ?? 0;\n  };\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions();\n    return !!subscriptions?.get(queryCacheKey)?.get(requestId);\n  };\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed\n  };\n  function serializeSubscriptions(currentSubscriptions: SubscriptionInternalState): SubscriptionState {\n    // We now use nested Maps for subscriptions, instead of\n    // plain Records. Stringify this accordingly so we can\n    // convert it to the shape we need for the store.\n    return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));\n  }\n  return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);\n    }\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = {};\n      internalState.currentSubscriptions.clear();\n      updateSyncTimer = null;\n      return [true, false];\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors];\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n    let actionShouldContinue = true;\n\n    // HACK Sneak the test-only polling state back out\n    if (process.env.NODE_ENV === 'test' && typeof action.type === 'string' && action.type === `${api.reducerPath}/getPolling`) {\n      return [false, internalState.currentPolls] as any;\n    }\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = serializeSubscriptions(internalState.currentSubscriptions);\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions;\n          updateSyncTimer = null;\n        }, 500);\n      }\n      const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n      const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n      actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n    }\n    return [actionShouldContinue, false];\n  };\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\n\n/**\n * @example\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => 'posts',\n *       // highlight-start\n *       keepUnusedDataFor: 5\n *       // highlight-end\n *     })\n *   })\n * })\n * ```\n */\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   */\n  keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectConfig\n  },\n  getRunningQueryThunk,\n  mwApi\n}) => {\n  const {\n    removeQueryResult,\n    unsubscribeQueryResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);\n    if (!subscriptions) {\n      return false;\n    }\n    const hasSubscriptions = subscriptions.size > 0;\n    return hasSubscriptions;\n  }\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n  function abortAllPromises<T extends {\n    abort?: () => void;\n  }>(promiseMap: Map<string, T | undefined>): void {\n    for (const promise of promiseMap.values()) {\n      promise?.abort?.();\n    }\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    const state = mwApi.getState();\n    const config = selectConfig(state);\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[];\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n      } else {\n        const {\n          queryCacheKey\n        } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n        queryCacheKeys = [queryCacheKey];\n      }\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n    }\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout);\n        delete currentRemovalTimeouts[key];\n      }\n      abortAllPromises(internalState.runningQueries);\n      abortAllPromises(internalState.runningMutations);\n    }\n    if (context.hasRehydrationInfo(action)) {\n      const {\n        queries\n      } = context.extractRehydrationInfo(action)!;\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n    }\n  };\n  function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n    const state = api.getState();\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey);\n      if (entry?.endpointName) {\n        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config);\n      }\n    }\n  }\n  function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string, api: SubMiddlewareApi, config: ConfigState<string>) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName) as QueryDefinition<any, any, any, any>;\n    const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return;\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n      if (currentTimeout) {\n        clearTimeout(currentTimeout);\n      }\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          // Try to abort any running query for this cache key\n          const entry = selectQueryEntry(api.getState(), queryCacheKey);\n          if (entry?.endpointName) {\n            const runningQuery = api.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));\n            runningQuery?.abort();\n          }\n          api.dispatch(removeQueryResult({\n            queryCacheKey\n          }));\n        }\n        delete currentRemovalTimeouts![queryCacheKey];\n      }, finalKeepUnusedDataFor * 1000);\n    }\n  }\n  return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta, BaseQueryResult } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition, DefinitionType } from '../../endpointDefinitions';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nimport { getEndpointDefinition } from '@internal/query/apiTypes';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<{\n    type: DefinitionType.query;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<{\n    type: DefinitionType.mutation;\n  } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, BaseQueryResult<BaseQuery>>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>;\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>;\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown;\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: MetaType;\n  }, typeof neverResolvedError>;\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: {\n    selectQueryEntry,\n    selectApiState\n  }\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk);\n  const isMutationThunk = isAsyncThunkAction(mutationThunk);\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    valueResolved?(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    cacheEntryRemoved(): void;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const {\n    removeQueryResult,\n    removeMutationResult,\n    cacheEntriesUpserted\n  } = api.internalActions;\n  function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta\n      });\n      delete lifecycle.valueResolved;\n    }\n  }\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey];\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey];\n      lifecycle.cacheEntryRemoved();\n    }\n  }\n  function getActionMetaFields(action: ReturnType<typeof queryThunk.pending> | ReturnType<typeof mutationThunk.pending>) {\n    const {\n      arg,\n      requestId\n    } = action.meta;\n    const {\n      endpointName,\n      originalArgs\n    } = arg;\n    return [endpointName, originalArgs, requestId] as const;\n  }\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey;\n    function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    }\n    if (queryThunk.pending.match(action)) {\n      const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);\n    } else if (cacheEntriesUpserted.match(action)) {\n      for (const {\n        queryDescription,\n        value\n      } of action.payload) {\n        const {\n          endpointName,\n          originalArgs,\n          queryCacheKey\n        } = queryDescription;\n        checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n        resolveLifecycleEntry(queryCacheKey, value, {});\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n      if (state) {\n        const [endpointName, originalArgs, requestId] = getActionMetaFields(action);\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n    } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {\n      removeLifecycleEntry(cacheKey);\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey);\n      }\n    }\n  };\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n    }\n    if (removeQueryResult.match(action)) return action.payload.queryCacheKey;\n    if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n    return '';\n  }\n  function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName);\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n    if (!onCacheEntryAdded) return;\n    const lifecycle = {} as CacheLifecycle;\n    const cacheEntryRemoved = new Promise<void>(resolve => {\n      lifecycle.cacheEntryRemoved = resolve;\n    });\n    const cacheDataLoaded: PromiseWithKnownReason<{\n      data: unknown;\n      meta: unknown;\n    }, typeof neverResolvedError> = Promise.race([new Promise<{\n      data: unknown;\n      meta: unknown;\n    }>(resolve => {\n      lifecycle.valueResolved = resolve;\n    }), cacheEntryRemoved.then(() => {\n      throw neverResolvedError;\n    })]);\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {});\n    lifecycleMap[queryCacheKey] = lifecycle;\n    const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);\n    const extra = mwApi.dispatch((_, __, extra) => extra);\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n      cacheDataLoaded,\n      cacheEntryRemoved\n    };\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch(e => {\n      if (e === neverResolvedError) return;\n      throw e;\n    });\n  }\n  return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: {\n    apiUid\n  },\n  reducerPath\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n      }\n    }\n  };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler } from './types';\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: {\n    endpointDefinitions\n  },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n  const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));\n  let pendingTagInvalidations: FullTagDescription<string>[] = [];\n  // Track via counter so we can avoid iterating over state every time\n  let pendingRequestCount = 0;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {\n      pendingRequestCount++;\n    }\n    if (isQueryEnd(action)) {\n      pendingRequestCount = Math.max(0, pendingRequestCount - 1);\n    }\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi);\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n    }\n  };\n  function hasPendingRequests() {\n    return pendingRequestCount > 0;\n  }\n  function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n    const rootState = mwApi.getState();\n    const state = rootState[reducerPath];\n    pendingTagInvalidations.push(...newTags);\n    if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests()) {\n      return;\n    }\n    const tags = pendingTagInvalidations;\n    pendingTagInvalidations = [];\n    if (tags.length === 0) return;\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values());\n      for (const {\n        queryCacheKey\n      } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey];\n        const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);\n        if (querySubState) {\n          if (subscriptionSubState.size === 0) {\n            mwApi.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            mwApi.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers, SubscribersInternal } from '../apiState';\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    currentPolls,\n    currentSubscriptions\n  } = internalState;\n\n  // Batching state for polling updates\n  const pendingPollingUpdates = new Set<string>();\n  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n      schedulePollingUpdate(action.payload.queryCacheKey, mwApi);\n    }\n    if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);\n    }\n    if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n      startNextPoll(action.meta.arg, mwApi);\n    }\n    if (api.util.resetApiState.match(action)) {\n      clearPolls();\n      // Clear any pending updates\n      if (pollingUpdateTimer) {\n        clearTimeout(pollingUpdateTimer);\n        pollingUpdateTimer = null;\n      }\n      pendingPollingUpdates.clear();\n    }\n  };\n  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {\n    pendingPollingUpdates.add(queryCacheKey);\n    if (!pollingUpdateTimer) {\n      pollingUpdateTimer = setTimeout(() => {\n        // Process all pending updates in a single batch\n        for (const key of pendingPollingUpdates) {\n          updatePollingInterval({\n            queryCacheKey: key as any\n          }, api);\n        }\n        pendingPollingUpdates.clear();\n        pollingUpdateTimer = null;\n      }, 0);\n    }\n  }\n  function startNextPoll({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;\n    const {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    } = findLowestPollingInterval(subscriptions);\n    if (!Number.isFinite(lowestPollingInterval)) return;\n    const currentPoll = currentPolls.get(queryCacheKey);\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout);\n      currentPoll.timeout = undefined;\n    }\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    currentPolls.set(queryCacheKey, {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState));\n        }\n        startNextPoll({\n          queryCacheKey\n        }, api);\n      }, lowestPollingInterval)\n    });\n  }\n  function updatePollingInterval({\n    queryCacheKey\n  }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n    const state = api.getState()[reducerPath];\n    const querySubState = state.queries[queryCacheKey];\n    const subscriptions = currentSubscriptions.get(queryCacheKey);\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {\n      return;\n    }\n    const {\n      lowestPollingInterval\n    } = findLowestPollingInterval(subscriptions);\n\n    // HACK add extra data to track how many times this has been called in tests\n    // yes we're mutating a nonexistent field on a Map here\n    if (process.env.NODE_ENV === 'test') {\n      const updateCounters = (currentPolls as any).pollUpdateCounters ??= {};\n      updateCounters[queryCacheKey] ??= 0;\n      updateCounters[queryCacheKey]++;\n    }\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey);\n      return;\n    }\n    const currentPoll = currentPolls.get(queryCacheKey);\n    const nextPollTimestamp = Date.now() + lowestPollingInterval;\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({\n        queryCacheKey\n      }, api);\n    }\n  }\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls.get(key);\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout);\n    }\n    currentPolls.delete(key);\n  }\n  function clearPolls() {\n    for (const key of currentPolls.keys()) {\n      cleanupPollForKey(key);\n    }\n  }\n  function findLowestPollingInterval(subscribers: SubscribersInternal = new Map()) {\n    let skipPollingIfUnfocused: boolean | undefined = false;\n    let lowestPollingInterval = Number.POSITIVE_INFINITY;\n    for (const entry of subscribers.values()) {\n      if (!!entry.pollingInterval) {\n        lowestPollingInterval = Math.min(entry.pollingInterval!, lowestPollingInterval);\n        skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;\n      }\n    }\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused\n    };\n  }\n  return handler;\n};","import { getEndpointDefinition } from '@internal/query/apiTypes';\nimport type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { isAnyQueryDefinition } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<{\n    /**\n     * The (transformed) query result.\n     */\n    data: ResultType;\n    /**\n     * The `meta` returned by the `baseQuery`\n     */\n    meta: BaseQueryMeta<BaseQuery>;\n  }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n  error: BaseQueryError<BaseQuery>;\n  /**\n   * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n   */\n  isUnhandledError: false;\n  /**\n   * The `meta` returned by the `baseQuery`\n   */\n  meta: BaseQueryMeta<BaseQuery>;\n} | {\n  error: unknown;\n  meta?: undefined;\n  /**\n   * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n   * There can not be made any assumption about the shape of `error`.\n   */\n  isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * import { messageCreated } from './notificationsSlice\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'))\n   *         try {\n   *           const { data } = await queryFulfilled\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'))\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'))\n   *         }\n   *       }\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n  /**\n   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk);\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n  type CacheLifecycle = {\n    resolve(value: {\n      data: unknown;\n      meta: unknown;\n    }): unknown;\n    reject(value: QueryFulfilledRejectionReason<any>): unknown;\n  };\n  const lifecycleMap: Record<string, CacheLifecycle> = {};\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: {\n          endpointName,\n          originalArgs\n        }\n      } = action.meta;\n      const endpointDefinition = getEndpointDefinition(context, endpointName);\n      const onQueryStarted = endpointDefinition?.onQueryStarted;\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle;\n        const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n          data: unknown;\n          meta: unknown;\n        }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n          lifecycle.resolve = resolve;\n          lifecycle.reject = reject;\n        });\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {});\n        lifecycleMap[requestId] = lifecycle;\n        const selector = (api.endpoints[endpointName] as any).select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);\n        const extra = mwApi.dispatch((_, __, extra) => extra);\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition) ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n          queryFulfilled\n        };\n        onQueryStarted(originalArgs, lifecycleApi as any);\n      }\n    } else if (isFullfilledThunk(action)) {\n      const {\n        requestId,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta\n      });\n      delete lifecycleMap[requestId];\n    } else if (isRejectedThunk(action)) {\n      const {\n        requestId,\n        rejectedWithValue,\n        baseQueryMeta\n      } = action.meta;\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any\n      });\n      delete lifecycleMap[requestId];\n    }\n  };\n  return handler;\n};","import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState\n}) => {\n  const {\n    removeQueryResult\n  } = api.internalActions;\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus');\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect');\n    }\n  };\n  function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n    const state = api.getState()[reducerPath];\n    const queries = state.queries;\n    const subscriptions = internalState.currentSubscriptions;\n    context.batch(() => {\n      for (const queryCacheKey of subscriptions.keys()) {\n        const querySubState = queries[queryCacheKey];\n        const subscriptionSubState = subscriptions.get(queryCacheKey);\n        if (!subscriptionSubState || !querySubState) continue;\n        const values = [...subscriptionSubState.values()];\n        const shouldRefetch = values.some(sub => sub[type] === true) || values.every(sub => sub[type] === undefined) && state.config[type];\n        if (shouldRefetch) {\n          if (subscriptionSubState.size === 0) {\n            api.dispatch(removeQueryResult({\n              queryCacheKey: queryCacheKey as QueryCacheKey\n            }));\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            api.dispatch(refetchQuery(querySubState));\n          }\n        }\n      }\n    });\n  }\n  return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const {\n    reducerPath,\n    queryThunk,\n    api,\n    context,\n    getInternalState\n  } = input;\n  const {\n    apiUid\n  } = context;\n  const actions = {\n    invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n  };\n  const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n  const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n  const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n    let initialized = false;\n    const internalState = getInternalState(mwApi.dispatch);\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction,\n      mwApi\n    };\n    const handlers = handlerBuilders.map(build => build(builderArgs));\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n    const windowEventsHandler = buildWindowEventHandler(builderArgs);\n    return next => {\n      return action => {\n        if (!isAction(action)) {\n          return next(action);\n        }\n        if (!initialized) {\n          initialized = true;\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n        }\n        const mwApiWithNext = {\n          ...mwApi,\n          next\n        };\n        const stateBefore = mwApi.getState();\n        const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n        let res: any;\n        if (actionShouldContinue) {\n          res = next(action);\n        } else {\n          res = internalProbeResult;\n        }\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore);\n          if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore);\n            }\n          }\n        }\n        return res;\n      };\n    };\n  };\n  return {\n    middleware,\n    actions\n  };\n  function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n    status: QueryStatus.uninitialized;\n  }>) {\n    return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true\n    });\n  }\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Dispatch, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from '../utils/immerImports';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryArgFromAnyQuery, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport type { InternalMiddlewareState } from './buildMiddleware/types';\nimport { getOrInsertComputed } from '../utils';\nimport type { CreateSelectorFunction } from 'reselect';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n */\nexport type PrefetchOptions = {\n  ifOlderThan?: false | number;\n} | {\n  force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath;\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions;\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n    /**\n     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'query';\n      }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n        type: 'infinitequery';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n        type: 'mutation';\n      }> | undefined>;\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n       *\n       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n      /**\n       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n       *\n       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n       *\n       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n       *\n       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n       *\n       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n      /**\n       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n       *\n       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n       *\n       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n      /**\n       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState'];\n      upsertQueryEntries: UpsertEntries<Definitions>;\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n       *\n       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n       *\n       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n        endpointName: string;\n        originalArgs: any;\n        queryCacheKey: string;\n      }>;\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;\n    };\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never };\n  };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string;\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline;\n  onOffline: typeof onOffline;\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus;\n  onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(api, {\n    baseQuery,\n    tagTypes,\n    reducerPath,\n    serializeQueryArgs,\n    keepUnusedDataFor,\n    refetchOnMountOrArgChange,\n    refetchOnFocus,\n    refetchOnReconnect,\n    invalidationBehavior,\n    onSchemaFailure,\n    catchSchemaFailure,\n    skipSchemaValidation\n  }, context) {\n    enablePatches();\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n    const assertTagType: AssertTagTypes = tag => {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n        }\n      }\n      return tag;\n    };\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost\n      },\n      util: {}\n    });\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector\n    });\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector\n    } = selectors;\n    safeAssign(api.util, {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery\n    });\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation\n    });\n    const {\n      reducer,\n      actions: sliceActions\n    } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior\n      }\n    });\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n    });\n    safeAssign(api.internalActions, sliceActions);\n    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>();\n    const getInternalState = (dispatch: Dispatch) => {\n      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({\n        currentSubscriptions: new Map(),\n        currentPolls: new Map(),\n        runningQueries: new Map(),\n        runningMutations: new Map()\n      }));\n      return state;\n    };\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context,\n      getInternalState\n    });\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk\n    });\n    const {\n      middleware,\n      actions: middlewareActions\n    } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors,\n      getRunningQueryThunk,\n      getInternalState\n    });\n    safeAssign(api.util, middlewareActions);\n    safeAssign(api, {\n      reducer: reducer as any,\n      middleware\n    });\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n        const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n        if (isQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildQuerySelector(endpointName, definition),\n            initiate: buildInitiateQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildMutationSelector(),\n            initiate: buildInitiateMutation(endpointName)\n          }, buildMatchThunkActions(mutationThunk, endpointName));\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(endpoint, {\n            name: endpointName,\n            select: buildInfiniteQuerySelector(endpointName, definition),\n            initiate: buildInitiateInfiniteQuery(endpointName, definition)\n          }, buildMatchThunkActions(queryThunk, endpointName));\n        }\n      }\n    };\n  }\n});","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":";AAkEO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,mBAAgB;AAChB,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,cAAW;AAJD,SAAAA;AAAA,GAAA;AAQL,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AA0BxB,SAAS,sBAAsB,QAAyC;AAC7E,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB,WAAW;AAAA,IAC5B,WAAW,WAAW;AAAA,IACtB,WAAW,WAAW;AAAA,IACtB,SAAS,WAAW;AAAA,EACtB;AACF;;;AC3GA,SAAS,cAAc,aAAa,gBAAgB,kBAAkB,iBAAiB,iBAAiB,SAAS,SAAS,UAAU,WAAW,YAAY,aAAa,qBAAqB,oBAAoB,oBAAoB,kBAAkB,eAAe,cAAc;;;ACDpR,IAAMC,iBA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AM;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,UAAM;AAAA,MACJ;AAAA,MACA,SAAS;AAAA,IACX,IAAI,gBAAgB;AAAA,MAClB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,eAAW,IAAI,MAAM,iBAAiB;AACtC,eAAW,KAAK;AAAA,MACd;AAAA,MACA;AAAA,IACF,CAAC;AACD,WAAO;AAAA,MACL,MAAM;AAAA,MACN,eAAe,cAAc,YAAY;AACvC,cAAM,SAAS;AACf,cAAM,WAAW,OAAO,UAAU,YAAY,MAAM,CAAC;AACrD,YAAI,kBAAkB,UAAU,GAAG;AACjC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,mBAAmB,cAAc,UAAU;AAAA,YACnD,UAAU,mBAAmB,cAAc,UAAU;AAAA,UACvD,GAAG,uBAAuB,YAAY,YAAY,CAAC;AAAA,QACrD;AACA,YAAI,qBAAqB,UAAU,GAAG;AACpC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,sBAAsB;AAAA,YAC9B,UAAU,sBAAsB,YAAY;AAAA,UAC9C,GAAG,uBAAuB,eAAe,YAAY,CAAC;AAAA,QACxD;AACA,YAAI,0BAA0B,UAAU,GAAG;AACzC,qBAAW,UAAU;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,2BAA2B,cAAc,UAAU;AAAA,YAC3D,UAAU,2BAA2B,cAAc,UAAU;AAAA,UAC/D,GAAG,uBAAuB,YAAY,YAAY,CAAC;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACniBO,IAAM,YAA2B,+BAAe,WAAW,CAAC;","names":["QueryStatus","isPlainObject","retry","updateListeners","arg","force","options","actions","createSelector","_formatProdErrorMessage","_formatProdErrorMessage2","key","queryArgsApi","_formatProdErrorMessage","getPreviousPageParam","_formatProdErrorMessage2","_formatProdErrorMessage","mwApi","mwApi","api","cacheKey","extra","api","extra","api","actions","initialized","createSelector"]}
Index: node_modules/@reduxjs/toolkit/dist/react/cjs/index.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+'use strict'
+if (process.env.NODE_ENV === 'production') {
+  module.exports = require('./redux-toolkit-react.production.min.cjs')
+} else {
+  module.exports = require('./redux-toolkit-react.development.cjs')
+}
Index: node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.development.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.development.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,55 @@
+"use strict";
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// src/react/index.ts
+var react_exports = {};
+__export(react_exports, {
+  createDynamicMiddleware: () => createDynamicMiddleware
+});
+module.exports = __toCommonJS(react_exports);
+__reExport(react_exports, require("@reduxjs/toolkit"), module.exports);
+
+// src/dynamicMiddleware/react/index.ts
+var import_toolkit = require("@reduxjs/toolkit");
+var import_react_redux = require("react-redux");
+var createDynamicMiddleware = () => {
+  const instance = (0, import_toolkit.createDynamicMiddleware)();
+  const createDispatchWithMiddlewareHookFactory = (context = import_react_redux.ReactReduxContext) => {
+    const useDispatch = context === import_react_redux.ReactReduxContext ? import_react_redux.useDispatch : (0, import_react_redux.createDispatchHook)(context);
+    function createDispatchWithMiddlewareHook2(...middlewares) {
+      instance.addMiddleware(...middlewares);
+      return useDispatch;
+    }
+    createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
+    return createDispatchWithMiddlewareHook2;
+  };
+  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
+  return {
+    ...instance,
+    createDispatchWithMiddlewareHookFactory,
+    createDispatchWithMiddlewareHook
+  };
+};
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+  createDynamicMiddleware,
+  ...require("@reduxjs/toolkit")
+});
+//# sourceMappingURL=redux-toolkit-react.development.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.development.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.development.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/react/index.ts","../../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n  <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n  createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n  const instance = cDM<State, DispatchType>();\n  const createDispatchWithMiddlewareHookFactory = (\n  // @ts-ignore\n  context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n    function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n      instance.addMiddleware(...middlewares);\n      return useDispatch;\n    }\n    createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  };\n  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n  return {\n    ...instance,\n    createDispatchWithMiddlewareHookFactory,\n    createDispatchWithMiddlewareHook\n  };\n};"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,0BAAc,6BAHd;;;ACCA,qBAA+C;AAG/C,yBAAyF;AAYlF,IAAM,0BAA0B,MAAgJ;AACrL,QAAM,eAAW,eAAAA,yBAAyB;AAC1C,QAAM,0CAA0C,CAEhD,UAA2F,yCAAsB;AAC/G,UAAM,cAAc,YAAY,uCAAoB,mBAAAC,kBAAqB,uCAAmB,OAAO;AACnG,aAASC,qCAAgG,aAA0B;AACjI,eAAS,cAAc,GAAG,WAAW;AACrC,aAAO;AAAA,IACT;AACA,IAAAA,kCAAiC,YAAY,MAAMA;AACnD,WAAOA;AAAA,EACT;AACA,QAAM,mCAAmC,wCAAwC;AACjF,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;","names":["cDM","useDefaultDispatch","createDispatchWithMiddlewareHook"]}
Index: node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.production.min.cjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.production.min.cjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+"use strict";var s=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var x=(t,e)=>{for(var a in e)s(t,a,{get:e[a],enumerable:!0})},d=(t,e,a,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of y(e))!M.call(t,i)&&i!==a&&s(t,i,{get:()=>e[i],enumerable:!(n=w(e,i))||n.enumerable});return t},r=(t,e,a)=>(d(t,e,"default"),a&&d(a,e,"default"));var m=t=>d(s({},"__esModule",{value:!0}),t);var o={};x(o,{createDynamicMiddleware:()=>D});module.exports=m(o);r(o,require("@reduxjs/toolkit"),module.exports);var h=require("@reduxjs/toolkit"),c=require("react-redux"),D=()=>{let t=(0,h.createDynamicMiddleware)(),e=(n=c.ReactReduxContext)=>{let i=n===c.ReactReduxContext?c.useDispatch:(0,c.createDispatchHook)(n);function p(...l){return t.addMiddleware(...l),i}return p.withTypes=()=>p,p},a=e();return{...t,createDispatchWithMiddlewareHookFactory:e,createDispatchWithMiddlewareHook:a}};0&&(module.exports={createDynamicMiddleware,...require("@reduxjs/toolkit")});
+//# sourceMappingURL=redux-toolkit-react.production.min.cjs.map
Index: node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.production.min.cjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/cjs/redux-toolkit-react.production.min.cjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../../src/react/index.ts","../../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n  <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n  createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n  const instance = cDM<State, DispatchType>();\n  const createDispatchWithMiddlewareHookFactory = (\n  // @ts-ignore\n  context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n    function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n      instance.addMiddleware(...middlewares);\n      return useDispatch;\n    }\n    createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  };\n  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n  return {\n    ...instance,\n    createDispatchWithMiddlewareHookFactory,\n    createDispatchWithMiddlewareHook\n  };\n};"],"mappings":"2dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,IAAA,eAAAC,EAAAH,GAGAI,EAAAJ,EAAc,4BAHd,gBCCA,IAAAK,EAA+C,4BAG/CC,EAAyF,uBAY5EC,EAA0B,IAAgJ,CACrL,IAAMC,KAAW,EAAAC,yBAAyB,EACpCC,EAA0C,CAEhDC,EAA2F,sBAAsB,CAC/G,IAAMC,EAAcD,IAAY,oBAAoB,EAAAE,eAAqB,sBAAmBF,CAAO,EACnG,SAASG,KAAgGC,EAA0B,CACjI,OAAAP,EAAS,cAAc,GAAGO,CAAW,EAC9BH,CACT,CACA,OAAAE,EAAiC,UAAY,IAAMA,EAC5CA,CACT,EACMA,EAAmCJ,EAAwC,EACjF,MAAO,CACL,GAAGF,EACH,wCAAAE,EACA,iCAAAI,CACF,CACF","names":["react_exports","__export","createDynamicMiddleware","__toCommonJS","__reExport","import_toolkit","import_react_redux","createDynamicMiddleware","instance","cDM","createDispatchWithMiddlewareHookFactory","context","useDispatch","useDefaultDispatch","createDispatchWithMiddlewareHook","middlewares"]}
Index: node_modules/@reduxjs/toolkit/dist/react/index.d.mts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/index.d.mts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,22 @@
+import { DynamicMiddlewareInstance, TSHelpersExtractDispatchExtensions, MiddlewareApiConfig, GetState, GetDispatch } from '@reduxjs/toolkit';
+export * from '@reduxjs/toolkit';
+import { Context } from 'react';
+import { ReactReduxContextValue } from 'react-redux';
+import { Dispatch, UnknownAction, Action, Middleware } from 'redux';
+
+type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;
+type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
+    <Middlewares extends [
+        Middleware<any, State, DispatchType>,
+        ...Middleware<any, State, DispatchType>[]
+    ]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;
+    withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;
+};
+type ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;
+type ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {
+    createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;
+    createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;
+};
+declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => ReactDynamicMiddlewareInstance<State, DispatchType>;
+
+export { type CreateDispatchWithMiddlewareHook, createDynamicMiddleware };
Index: node_modules/@reduxjs/toolkit/dist/react/index.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/index.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,22 @@
+import { DynamicMiddlewareInstance, TSHelpersExtractDispatchExtensions, MiddlewareApiConfig, GetState, GetDispatch } from '@reduxjs/toolkit';
+export * from '@reduxjs/toolkit';
+import { Context } from 'react';
+import { ReactReduxContextValue } from 'react-redux';
+import { Dispatch, UnknownAction, Action, Middleware } from 'redux';
+
+type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;
+type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
+    <Middlewares extends [
+        Middleware<any, State, DispatchType>,
+        ...Middleware<any, State, DispatchType>[]
+    ]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;
+    withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;
+};
+type ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;
+type ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {
+    createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;
+    createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;
+};
+declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => ReactDynamicMiddlewareInstance<State, DispatchType>;
+
+export { type CreateDispatchWithMiddlewareHook, createDynamicMiddleware };
Index: node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.browser.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+export*from"@reduxjs/toolkit";import{createDynamicMiddleware as p}from"@reduxjs/toolkit";import{createDispatchHook as d,ReactReduxContext as c,useDispatch as s}from"react-redux";var h=()=>{let t=p(),a=(i=c)=>{let o=i===c?s:d(i);function e(...r){return t.addMiddleware(...r),o}return e.withTypes=()=>e,e},n=a();return{...t,createDispatchWithMiddlewareHookFactory:a,createDispatchWithMiddlewareHook:n}};export{h as createDynamicMiddleware};
+//# sourceMappingURL=redux-toolkit-react.browser.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.browser.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n  <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n  createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n  const instance = cDM<State, DispatchType>();\n  const createDispatchWithMiddlewareHookFactory = (\n  // @ts-ignore\n  context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n    function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n      instance.addMiddleware(...middlewares);\n      return useDispatch;\n    }\n    createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  };\n  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n  return {\n    ...instance,\n    createDispatchWithMiddlewareHookFactory,\n    createDispatchWithMiddlewareHook\n  };\n};"],"mappings":"AAGA,WAAc,mBCFd,OAAS,2BAA2BA,MAAW,mBAG/C,OAAS,sBAAAC,EAAoB,qBAAAC,EAAmB,eAAeC,MAA0B,cAYlF,IAAMC,EAA0B,IAAgJ,CACrL,IAAMC,EAAWL,EAAyB,EACpCM,EAA0C,CAEhDC,EAA2FL,IAAsB,CAC/G,IAAMM,EAAcD,IAAYL,EAAoBC,EAAqBF,EAAmBM,CAAO,EACnG,SAASE,KAAgGC,EAA0B,CACjI,OAAAL,EAAS,cAAc,GAAGK,CAAW,EAC9BF,CACT,CACA,OAAAC,EAAiC,UAAY,IAAMA,EAC5CA,CACT,EACMA,EAAmCH,EAAwC,EACjF,MAAO,CACL,GAAGD,EACH,wCAAAC,EACA,iCAAAG,CACF,CACF","names":["cDM","createDispatchHook","ReactReduxContext","useDefaultDispatch","createDynamicMiddleware","instance","createDispatchWithMiddlewareHookFactory","context","useDispatch","createDispatchWithMiddlewareHook","middlewares"]}
Index: node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.legacy-esm.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,47 @@
+var __defProp = Object.defineProperty;
+var __defProps = Object.defineProperties;
+var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
+var __getOwnPropSymbols = Object.getOwnPropertySymbols;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __propIsEnum = Object.prototype.propertyIsEnumerable;
+var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __spreadValues = (a, b) => {
+  for (var prop in b || (b = {}))
+    if (__hasOwnProp.call(b, prop))
+      __defNormalProp(a, prop, b[prop]);
+  if (__getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(b)) {
+      if (__propIsEnum.call(b, prop))
+        __defNormalProp(a, prop, b[prop]);
+    }
+  return a;
+};
+var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
+
+// src/react/index.ts
+export * from "@reduxjs/toolkit";
+
+// src/dynamicMiddleware/react/index.ts
+import { createDynamicMiddleware as cDM } from "@reduxjs/toolkit";
+import { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from "react-redux";
+var createDynamicMiddleware = () => {
+  const instance = cDM();
+  const createDispatchWithMiddlewareHookFactory = (context = ReactReduxContext) => {
+    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);
+    function createDispatchWithMiddlewareHook2(...middlewares) {
+      instance.addMiddleware(...middlewares);
+      return useDispatch;
+    }
+    createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
+    return createDispatchWithMiddlewareHook2;
+  };
+  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
+  return __spreadProps(__spreadValues({}, instance), {
+    createDispatchWithMiddlewareHookFactory,
+    createDispatchWithMiddlewareHook
+  });
+};
+export {
+  createDynamicMiddleware
+};
+//# sourceMappingURL=redux-toolkit-react.legacy-esm.js.map
Index: node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.legacy-esm.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n  <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n  createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n  const instance = cDM<State, DispatchType>();\n  const createDispatchWithMiddlewareHookFactory = (\n  // @ts-ignore\n  context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n    function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n      instance.addMiddleware(...middlewares);\n      return useDispatch;\n    }\n    createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  };\n  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n  return {\n    ...instance,\n    createDispatchWithMiddlewareHookFactory,\n    createDispatchWithMiddlewareHook\n  };\n};"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGA,cAAc;;;ACFd,SAAS,2BAA2B,WAAW;AAG/C,SAAS,oBAAoB,mBAAmB,eAAe,0BAA0B;AAYlF,IAAM,0BAA0B,MAAgJ;AACrL,QAAM,WAAW,IAAyB;AAC1C,QAAM,0CAA0C,CAEhD,UAA2F,sBAAsB;AAC/G,UAAM,cAAc,YAAY,oBAAoB,qBAAqB,mBAAmB,OAAO;AACnG,aAASA,qCAAgG,aAA0B;AACjI,eAAS,cAAc,GAAG,WAAW;AACrC,aAAO;AAAA,IACT;AACA,IAAAA,kCAAiC,YAAY,MAAMA;AACnD,WAAOA;AAAA,EACT;AACA,QAAM,mCAAmC,wCAAwC;AACjF,SAAO,iCACF,WADE;AAAA,IAEL;AAAA,IACA;AAAA,EACF;AACF;","names":["createDispatchWithMiddlewareHook"]}
Index: node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.modern.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,28 @@
+// src/react/index.ts
+export * from "@reduxjs/toolkit";
+
+// src/dynamicMiddleware/react/index.ts
+import { createDynamicMiddleware as cDM } from "@reduxjs/toolkit";
+import { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from "react-redux";
+var createDynamicMiddleware = () => {
+  const instance = cDM();
+  const createDispatchWithMiddlewareHookFactory = (context = ReactReduxContext) => {
+    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);
+    function createDispatchWithMiddlewareHook2(...middlewares) {
+      instance.addMiddleware(...middlewares);
+      return useDispatch;
+    }
+    createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
+    return createDispatchWithMiddlewareHook2;
+  };
+  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
+  return {
+    ...instance,
+    createDispatchWithMiddlewareHookFactory,
+    createDispatchWithMiddlewareHook
+  };
+};
+export {
+  createDynamicMiddleware
+};
+//# sourceMappingURL=redux-toolkit-react.modern.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.modern.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/react/redux-toolkit-react.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/react/index.ts","../../src/dynamicMiddleware/react/index.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit';\nexport * from '@reduxjs/toolkit';\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react';\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index';","import type { DynamicMiddlewareInstance, GetDispatch, GetState, MiddlewareApiConfig, TSHelpersExtractDispatchExtensions } from '@reduxjs/toolkit';\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit';\nimport type { Context } from 'react';\nimport type { ReactReduxContextValue } from 'react-redux';\nimport { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from 'react-redux';\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux';\nexport type UseDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[] = [], State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType;\nexport type CreateDispatchWithMiddlewareHook<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {\n  <Middlewares extends [Middleware<any, State, DispatchType>, ...Middleware<any, State, DispatchType>[]]>(...middlewares: Middlewares): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>;\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): CreateDispatchWithMiddlewareHook<GetState<MiddlewareConfig>, GetDispatch<MiddlewareConfig>>;\n};\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> = DispatchType extends Dispatch<infer Action> ? Action : never;\ntype ReactDynamicMiddlewareInstance<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = DynamicMiddlewareInstance<State, DispatchType> & {\n  createDispatchWithMiddlewareHookFactory: (context?: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null>) => CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<State, DispatchType>;\n};\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n  const instance = cDM<State, DispatchType>();\n  const createDispatchWithMiddlewareHookFactory = (\n  // @ts-ignore\n  context: Context<ReactReduxContextValue<State, ActionFromDispatch<DispatchType>> | null> = ReactReduxContext) => {\n    const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);\n    function createDispatchWithMiddlewareHook<Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares) {\n      instance.addMiddleware(...middlewares);\n      return useDispatch;\n    }\n    createDispatchWithMiddlewareHook.withTypes = () => createDispatchWithMiddlewareHook;\n    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<State, DispatchType>;\n  };\n  const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();\n  return {\n    ...instance,\n    createDispatchWithMiddlewareHookFactory,\n    createDispatchWithMiddlewareHook\n  };\n};"],"mappings":";AAGA,cAAc;;;ACFd,SAAS,2BAA2B,WAAW;AAG/C,SAAS,oBAAoB,mBAAmB,eAAe,0BAA0B;AAYlF,IAAM,0BAA0B,MAAgJ;AACrL,QAAM,WAAW,IAAyB;AAC1C,QAAM,0CAA0C,CAEhD,UAA2F,sBAAsB;AAC/G,UAAM,cAAc,YAAY,oBAAoB,qBAAqB,mBAAmB,OAAO;AACnG,aAASA,qCAAgG,aAA0B;AACjI,eAAS,cAAc,GAAG,WAAW;AACrC,aAAO;AAAA,IACT;AACA,IAAAA,kCAAiC,YAAY,MAAMA;AACnD,WAAOA;AAAA,EACT;AACA,QAAM,mCAAmC,wCAAwC;AACjF,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;","names":["createDispatchWithMiddlewareHook"]}
Index: node_modules/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3 @@
+export*from"redux";import{freeze as wa,original as Pa}from"immer";import{current as G,isDraft as v,produce as F,isDraftable as Q,setUseStrictIteration as ln}from"immer";import{createSelector as Ia,lruMemoize as va}from"reselect";import{createSelectorCreator as pe,weakMapMemoize as fe}from"reselect";var Ie=(...e)=>{let t=pe(...e),r=Object.assign((...n)=>{let a=t(...n),o=(i,...h)=>a(v(i)?G(i):i,...h);return Object.assign(o,a),o},{withTypes:()=>r});return r},ye=Ie(fe);import{createStore as ve,combineReducers as De,applyMiddleware as Oe,compose as V,isPlainObject as Y,isAction as B}from"redux";var Ne=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?V:V.apply(null,arguments)},kn=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__?window.__REDUX_DEVTOOLS_EXTENSION__:function(){return function(e){return e}};import{thunk as kt,withExtraArgument as gt}from"redux-thunk";var Z=e=>e&&typeof e.match=="function";function P(e,t){function r(...n){if(t){let a=t(...n);if(!a)throw new Error(C(0));return{type:e,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:e,payload:n[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=n=>B(n)&&n.type===e,r}function he(e){return typeof e=="function"&&"type"in e&&Z(e)}function Ae(e){return B(e)&&Object.keys(e).every(yt)}function yt(e){return["type","payload","error","meta"].indexOf(e)>-1}function ht(e){let t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}function At(e={}){return()=>r=>n=>r(n)}var L=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...t){return super.concat.apply(this,t)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Te(e){return Q(e)?F(e,()=>{}):e}function M(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function Tt(e){return typeof e!="object"||e==null||Object.isFrozen(e)}function mt(e={}){if(1)return()=>n=>a=>n(a);var t,r}function je(e){let t=typeof e;return e==null||t==="string"||t==="boolean"||t==="number"||Array.isArray(e)||Y(e)}function Fe(e,t="",r=je,n,a=[],o){let i;if(!r(e))return{keyPath:t||"<root>",value:e};if(typeof e!="object"||e===null||o?.has(e))return!1;let h=n!=null?n(e):Object.entries(e),s=a.length>0;for(let[c,y]of h){let A=t?t+"."+c:c;if(!(s&&a.some(f=>f instanceof RegExp?f.test(A):A===f))){if(!r(y))return{keyPath:A,value:y};if(typeof y=="object"&&(i=Fe(y,A,r,n,a,o),i))return i}}return o&&Ve(e)&&o.add(e),!1}function Ve(e){if(!Object.isFrozen(e))return!1;for(let t of Object.values(e))if(!(typeof t!="object"||t===null)&&!Ve(t))return!1;return!0}function St(e={}){return()=>t=>r=>t(r)}function xt(e){return typeof e=="boolean"}var Le=()=>function(t){let{thunk:r=!0,immutableCheck:n=!0,serializableCheck:a=!0,actionCreatorCheck:o=!0}=t??{},i=new L;return r&&(xt(r)?i.push(kt):i.push(gt(r.extraArgument))),i};var me="RTK_autoBatch",Ct=()=>e=>({payload:e,meta:{[me]:!0}}),_e=e=>t=>{setTimeout(t,e)},Se=(e={type:"raf"})=>t=>(...r)=>{let n=t(...r),a=!0,o=!1,i=!1,h=new Set,s=e.type==="tick"?queueMicrotask:e.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:_e(10):e.type==="callback"?e.queueNotification:_e(e.timeout),c=()=>{i=!1,o&&(o=!1,h.forEach(y=>y()))};return Object.assign({},n,{subscribe(y){let A=()=>a&&y(),S=n.subscribe(A);return h.add(y),()=>{S(),h.delete(y)}},dispatch(y){try{return a=!y?.meta?.[me],o=!a,o&&(i||(i=!0,s(c))),n.dispatch(y)}finally{a=!0}}})};var Ue=e=>function(r){let{autoBatch:n=!0}=r??{},a=new L(e);return n&&a.push(Se(typeof n=="object"?n:void 0)),a};function Et(e){let t=Le(),{reducer:r=void 0,middleware:n,devTools:a=!0,duplicateMiddlewareCheck:o=!0,preloadedState:i=void 0,enhancers:h=void 0}=e||{},s;if(typeof r=="function")s=r;else if(Y(r))s=De(r);else throw new Error(C(1));let c;typeof n=="function"?c=n(t):c=t();let y=V;a&&(y=Ne({trace:!1,...typeof a=="object"&&a}));let A=Oe(...c),S=Ue(A),f=typeof h=="function"?h(S):S(),d=y(...f);return ve(s,i,d)}function ee(e){let t={},r=[],n,a={addCase(o,i){let h=typeof o=="string"?o:o.type;if(!h)throw new Error(C(28));if(h in t)throw new Error(C(29));return t[h]=i,a},addAsyncThunk(o,i){return i.pending&&(t[o.pending.type]=i.pending),i.rejected&&(t[o.rejected.type]=i.rejected),i.fulfilled&&(t[o.fulfilled.type]=i.fulfilled),i.settled&&r.push({matcher:o.settled,reducer:i.settled}),a},addMatcher(o,i){return r.push({matcher:o,reducer:i}),a},addDefaultCase(o){return n=o,a}};return e(a),[t,r,n]}function Rt(e){return typeof e=="function"}function ke(e,t){let[r,n,a]=ee(t),o;if(Rt(e))o=()=>Te(e());else{let h=Te(e);o=()=>h}function i(h=o(),s){let c=[r[s.type],...n.filter(({matcher:y})=>y(s)).map(({reducer:y})=>y)];return c.filter(y=>!!y).length===0&&(c=[a]),c.reduce((y,A)=>{if(A)if(v(y)){let f=A(y,s);return f===void 0?y:f}else{if(Q(y))return F(y,S=>A(S,s));{let S=A(y,s);if(S===void 0){if(y===null)return y;throw Error("A case reducer on a non-draftable value must not return undefined")}return S}}return y},h)}return i.getInitialState=o,i}var We=(e,t)=>Z(e)?e.match(t):e(t);function _(...e){return t=>e.some(r=>We(r,t))}function K(...e){return t=>e.every(r=>We(r,t))}function ne(e,t){if(!e||!e.meta)return!1;let r=typeof e.meta.requestId=="string",n=t.indexOf(e.meta.requestStatus)>-1;return r&&n}function H(e){return typeof e[0]=="function"&&"pending"in e[0]&&"fulfilled"in e[0]&&"rejected"in e[0]}function ze(...e){return e.length===0?t=>ne(t,["pending"]):H(e)?_(...e.map(t=>t.pending)):ze()(e[0])}function te(...e){return e.length===0?t=>ne(t,["rejected"]):H(e)?_(...e.map(t=>t.rejected)):te()(e[0])}function Ge(...e){let t=r=>r&&r.meta&&r.meta.rejectedWithValue;return e.length===0?K(te(...e),t):H(e)?K(te(...e),t):Ge()(e[0])}function Be(...e){return e.length===0?t=>ne(t,["fulfilled"]):H(e)?_(...e.map(t=>t.fulfilled)):Be()(e[0])}function Ke(...e){return e.length===0?t=>ne(t,["pending","fulfilled","rejected"]):H(e)?_(...e.flatMap(t=>[t.pending,t.rejected,t.fulfilled])):Ke()(e[0])}var wt="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",D=(e=21)=>{let t="",r=e;for(;r--;)t+=wt[Math.random()*64|0];return t};var Pt=["name","message","stack","code"],q=class{constructor(t,r){this.payload=t;this.meta=r}_type},re=class{constructor(t,r){this.payload=t;this.meta=r}_type},qe=e=>{if(typeof e=="object"&&e!==null){let t={};for(let r of Pt)typeof e[r]=="string"&&(t[r]=e[r]);return t}return{message:String(e)}},He="External signal was aborted",ge=(()=>{function e(t,r,n){let a=P(t+"/fulfilled",(s,c,y,A)=>({payload:s,meta:{...A||{},arg:y,requestId:c,requestStatus:"fulfilled"}})),o=P(t+"/pending",(s,c,y)=>({payload:void 0,meta:{...y||{},arg:c,requestId:s,requestStatus:"pending"}})),i=P(t+"/rejected",(s,c,y,A,S)=>({payload:A,error:(n&&n.serializeError||qe)(s||"Rejected"),meta:{...S||{},arg:y,requestId:c,rejectedWithValue:!!A,requestStatus:"rejected",aborted:s?.name==="AbortError",condition:s?.name==="ConditionError"}}));function h(s,{signal:c}={}){return(y,A,S)=>{let f=n?.idGenerator?n.idGenerator(s):D(),d=new AbortController,l,u;function p(T){u=T,d.abort()}c&&(c.aborted?p(He):c.addEventListener("abort",()=>p(He),{once:!0}));let g=async function(){let T;try{let k=n?.condition?.(s,{getState:A,extra:S});if(Mt(k)&&(k=await k),k===!1||d.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};let R=new Promise((x,E)=>{l=()=>{E({name:"AbortError",message:u||"Aborted"})},d.signal.addEventListener("abort",l,{once:!0})});y(o(f,s,n?.getPendingMeta?.({requestId:f,arg:s},{getState:A,extra:S}))),T=await Promise.race([R,Promise.resolve(r(s,{dispatch:y,getState:A,extra:S,requestId:f,signal:d.signal,abort:p,rejectWithValue:(x,E)=>new q(x,E),fulfillWithValue:(x,E)=>new re(x,E)})).then(x=>{if(x instanceof q)throw x;return x instanceof re?a(x.payload,f,s,x.meta):a(x,f,s)})])}catch(k){T=k instanceof q?i(null,f,s,k.payload,k.meta):i(k,f,s)}finally{l&&d.signal.removeEventListener("abort",l)}return n&&!n.dispatchConditionRejection&&i.match(T)&&T.meta.condition||y(T),T}();return Object.assign(g,{abort:p,requestId:f,arg:s,unwrap(){return g.then($e)}})}}return Object.assign(h,{pending:o,rejected:i,fulfilled:a,settled:_(i,a),typePrefix:t})}return e.withTypes=()=>e,e})();function $e(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}function Mt(e){return e!==null&&typeof e=="object"&&typeof e.then=="function"}var Xe=Symbol.for("rtk-slice-createasyncthunk"),bt={[Xe]:ge},Je=(n=>(n.reducer="reducer",n.reducerWithPrepare="reducerWithPrepare",n.asyncThunk="asyncThunk",n))(Je||{});function It(e,t){return`${e}/${t}`}function Qe({creators:e}={}){let t=e?.asyncThunk?.[Xe];return function(n){let{name:a,reducerPath:o=a}=n;if(!a)throw new Error(C(11));let i=(typeof n.reducers=="function"?n.reducers(Ot()):n.reducers)||{},h=Object.keys(i),s={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},c={addCase(T,m){let k=typeof T=="string"?T:T.type;if(!k)throw new Error(C(12));if(k in s.sliceCaseReducersByType)throw new Error(C(13));return s.sliceCaseReducersByType[k]=m,c},addMatcher(T,m){return s.sliceMatchers.push({matcher:T,reducer:m}),c},exposeAction(T,m){return s.actionCreators[T]=m,c},exposeCaseReducer(T,m){return s.sliceCaseReducersByName[T]=m,c}};h.forEach(T=>{let m=i[T],k={reducerName:T,type:It(a,T),createNotation:typeof n.reducers=="function"};jt(m)?Vt(k,m,c,t):Nt(k,m,c)});function y(){let[T={},m=[],k=void 0]=typeof n.extraReducers=="function"?ee(n.extraReducers):[n.extraReducers],R={...T,...s.sliceCaseReducersByType};return ke(n.initialState,x=>{for(let E in R)x.addCase(E,R[E]);for(let E of s.sliceMatchers)x.addMatcher(E.matcher,E.reducer);for(let E of m)x.addMatcher(E.matcher,E.reducer);k&&x.addDefaultCase(k)})}let A=T=>T,S=new Map,f=new WeakMap,d;function l(T,m){return d||(d=y()),d(T,m)}function u(){return d||(d=y()),d.getInitialState()}function p(T,m=!1){function k(x){let E=x[T];return typeof E>"u"&&m&&(E=M(f,k,u)),E}function R(x=A){let E=M(S,m,()=>new WeakMap);return M(E,x,()=>{let z={};for(let[J,j]of Object.entries(n.selectors??{}))z[J]=vt(j,x,()=>M(f,x,u),m);return z})}return{reducerPath:T,getSelectors:R,get selectors(){return R(k)},selectSlice:k}}let g={name:a,reducer:l,actions:s.actionCreators,caseReducers:s.sliceCaseReducersByName,getInitialState:u,...p(o),injectInto(T,{reducerPath:m,...k}={}){let R=m??o;return T.inject({reducerPath:R,reducer:l},k),{...g,...p(R,!0)}}};return g}}function vt(e,t,r,n){function a(o,...i){let h=t(o);return typeof h>"u"&&n&&(h=r()),e(h,...i)}return a.unwrapped=e,a}var Dt=Qe();function Ot(){function e(t,r){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...r}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...r){return t(...r)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,r){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:r}},asyncThunk:e}}function Nt({type:e,reducerName:t,createNotation:r},n,a){let o,i;if("reducer"in n){if(r&&!Ft(n))throw new Error(C(17));o=n.reducer,i=n.prepare}else o=n;a.addCase(e,o).exposeCaseReducer(t,o).exposeAction(t,i?P(e,i):P(e))}function jt(e){return e._reducerDefinitionType==="asyncThunk"}function Ft(e){return e._reducerDefinitionType==="reducerWithPrepare"}function Vt({type:e,reducerName:t},r,n,a){if(!a)throw new Error(C(18));let{payloadCreator:o,fulfilled:i,pending:h,rejected:s,settled:c,options:y}=r,A=a(e,o,y);n.exposeAction(t,A),i&&n.addCase(A.fulfilled,i),h&&n.addCase(A.pending,h),s&&n.addCase(A.rejected,s),c&&n.addMatcher(A.settled,c),n.exposeCaseReducer(t,{fulfilled:i||ae,pending:h||ae,rejected:s||ae,settled:c||ae})}function ae(){}function Lt(){return{ids:[],entities:{}}}function Ye(e){function t(r={},n){let a=Object.assign(Lt(),r);return n?e.setAll(a,n):a}return{getInitialState:t}}function Ze(){function e(t,r={}){let{createSelector:n=ye}=r,a=A=>A.ids,o=A=>A.entities,i=n(a,o,(A,S)=>A.map(f=>S[f])),h=(A,S)=>S,s=(A,S)=>A[S],c=n(a,A=>A.length);if(!t)return{selectIds:a,selectEntities:o,selectAll:i,selectTotal:c,selectById:n(o,h,s)};let y=n(t,o);return{selectIds:n(t,a),selectEntities:y,selectAll:n(t,i),selectTotal:n(t,c),selectById:n(y,h,s)}}return{getSelectors:e}}var _t=v;function et(e){let t=w((r,n)=>e(n));return function(n){return t(n,void 0)}}function w(e){return function(r,n){function a(i){return Ae(i)}let o=i=>{a(n)?e(n.payload,i):e(n,i)};return _t(r)?(o(r),r):F(r,o)}}function O(e,t){return t(e)}function b(e){return Array.isArray(e)||(e=Object.values(e)),e}function $(e){return v(e)?G(e):e}function oe(e,t,r){e=b(e);let n=$(r.ids),a=new Set(n),o=[],i=new Set([]),h=[];for(let s of e){let c=O(s,t);a.has(c)||i.has(c)?h.push({id:c,changes:s}):(i.add(c),o.push(s))}return[o,h,n]}function ie(e){function t(d,l){let u=O(d,e);u in l.entities||(l.ids.push(u),l.entities[u]=d)}function r(d,l){d=b(d);for(let u of d)t(u,l)}function n(d,l){let u=O(d,e);u in l.entities||l.ids.push(u),l.entities[u]=d}function a(d,l){d=b(d);for(let u of d)n(u,l)}function o(d,l){d=b(d),l.ids=[],l.entities={},r(d,l)}function i(d,l){return h([d],l)}function h(d,l){let u=!1;d.forEach(p=>{p in l.entities&&(delete l.entities[p],u=!0)}),u&&(l.ids=l.ids.filter(p=>p in l.entities))}function s(d){Object.assign(d,{ids:[],entities:{}})}function c(d,l,u){let p=u.entities[l.id];if(p===void 0)return!1;let g=Object.assign({},p,l.changes),T=O(g,e),m=T!==l.id;return m&&(d[l.id]=T,delete u.entities[l.id]),u.entities[T]=g,m}function y(d,l){return A([d],l)}function A(d,l){let u={},p={};d.forEach(T=>{T.id in l.entities&&(p[T.id]={id:T.id,changes:{...p[T.id]?.changes,...T.changes}})}),d=Object.values(p),d.length>0&&d.filter(m=>c(u,m,l)).length>0&&(l.ids=Object.values(l.entities).map(m=>O(m,e)))}function S(d,l){return f([d],l)}function f(d,l){let[u,p]=oe(d,e,l);r(u,l),A(p,l)}return{removeAll:et(s),addOne:w(t),addMany:w(r),setOne:w(n),setMany:w(a),setAll:w(o),updateOne:w(y),updateMany:w(A),upsertOne:w(S),upsertMany:w(f),removeOne:w(i),removeMany:w(h)}}function Ut(e,t,r){let n=0,a=e.length;for(;n<a;){let o=n+a>>>1,i=e[o];r(t,i)>=0?n=o+1:a=o}return n}function Wt(e,t,r){let n=Ut(e,t,r);return e.splice(n,0,t),e}function tt(e,t){let{removeOne:r,removeMany:n,removeAll:a}=ie(e);function o(u,p){return i([u],p)}function i(u,p,g){u=b(u);let T=new Set(g??$(p.ids)),m=new Set,k=u.filter(R=>{let x=O(R,e),E=!m.has(x);return E&&m.add(x),!T.has(x)&&E});k.length!==0&&l(p,k)}function h(u,p){return s([u],p)}function s(u,p){let g={};if(u=b(u),u.length!==0){for(let T of u){let m=e(T);g[m]=T,delete p.entities[m]}u=b(g),l(p,u)}}function c(u,p){u=b(u),p.entities={},p.ids=[],i(u,p,[])}function y(u,p){return A([u],p)}function A(u,p){let g=!1,T=!1;for(let m of u){let k=p.entities[m.id];if(!k)continue;g=!0,Object.assign(k,m.changes);let R=e(k);if(m.id!==R){T=!0,delete p.entities[m.id];let x=p.ids.indexOf(m.id);p.ids[x]=R,p.entities[R]=k}}g&&l(p,[],g,T)}function S(u,p){return f([u],p)}function f(u,p){let[g,T,m]=oe(u,e,p);g.length&&i(g,p,m),T.length&&A(T,p)}function d(u,p){if(u.length!==p.length)return!1;for(let g=0;g<u.length;g++)if(u[g]!==p[g])return!1;return!0}let l=(u,p,g,T)=>{let m=$(u.entities),k=$(u.ids),R=u.entities,x=k;T&&(x=new Set(k));let E=[];for(let j of x){let be=m[j];be&&E.push(be)}let z=E.length===0;for(let j of p)R[e(j)]=j,z||Wt(E,j,t);z?E=p.slice().sort(t):g&&E.sort(t);let J=E.map(e);d(k,J)||(u.ids=J)};return{removeOne:r,removeMany:n,removeAll:a,addOne:w(o),updateOne:w(y),upsertOne:w(S),setOne:w(h),setMany:w(s),setAll:w(c),addMany:w(i),updateMany:w(A),upsertMany:w(f)}}function zt(e={}){let{selectId:t,sortComparer:r}={sortComparer:!1,selectId:i=>i.id,...e},n=r?tt(t,r):ie(t),a=Ye(n),o=Ze();return{selectId:t,sortComparer:r,...a,...o,...n}}var Gt="task",nt="listener",rt="completed",xe="cancelled",at=`task-${xe}`,ot=`task-${rt}`,se=`${nt}-${xe}`,it=`${nt}-${rt}`,I=class{constructor(t){this.code=t;this.message=`${Gt} ${xe} (reason: ${t})`}name="TaskAbortError";message};var ce=(e,t)=>{if(typeof e!="function")throw new TypeError(C(32))},U=()=>{},de=(e,t=U)=>(e.catch(t),e),ue=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t));var N=e=>{if(e.aborted)throw new I(e.reason)};function Ce(e,t){let r=U;return new Promise((n,a)=>{let o=()=>a(new I(e.reason));if(e.aborted){o();return}r=ue(e,o),t.finally(()=>r()).then(n,a)}).finally(()=>{r=U})}var st=async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(r){return{status:r instanceof I?"cancelled":"rejected",error:r}}finally{t?.()}},X=e=>t=>de(Ce(e,t).then(r=>(N(e),r))),Ee=e=>{let t=X(e);return r=>t(new Promise(n=>setTimeout(n,r)))};var{assign:W}=Object,ct={},le="listenerMiddleware",Bt=(e,t)=>{let r=n=>ue(e,()=>n.abort(e.reason));return(n,a)=>{ce(n,"taskExecutor");let o=new AbortController;r(o);let i=st(async()=>{N(e),N(o.signal);let h=await n({pause:X(o.signal),delay:Ee(o.signal),signal:o.signal});return N(o.signal),h},()=>o.abort(ot));return a?.autoJoin&&t.push(i.catch(U)),{result:X(e)(i),cancel(){o.abort(at)}}}},Kt=(e,t)=>{let r=async(n,a)=>{N(t);let o=()=>{},h=[new Promise((s,c)=>{let y=e({predicate:n,effect:(A,S)=>{S.unsubscribe(),s([A,S.getState(),S.getOriginalState()])}});o=()=>{y(),c()}})];a!=null&&h.push(new Promise(s=>setTimeout(s,a,null)));try{let s=await Ce(t,Promise.race(h));return N(t),s}finally{o()}};return(n,a)=>de(r(n,a))},lt=e=>{let{type:t,actionCreator:r,matcher:n,predicate:a,effect:o}=e;if(t)a=P(t).match;else if(r)t=r.type,a=r.match;else if(n)a=n;else if(!a)throw new Error(C(21));return ce(o,"options.listener"),{predicate:a,type:t,effect:o}},pt=W(e=>{let{type:t,predicate:r,effect:n}=lt(e);return{id:D(),effect:n,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error(C(22))}}},{withTypes:()=>pt}),dt=(e,t)=>{let{type:r,effect:n,predicate:a}=lt(t);return Array.from(e.values()).find(o=>(typeof r=="string"?o.type===r:o.predicate===a)&&o.effect===n)},Re=e=>{e.pending.forEach(t=>{t.abort(se)})},Ht=(e,t)=>()=>{for(let r of t.keys())Re(r);e.clear()},ut=(e,t,r)=>{try{e(t,r)}catch(n){setTimeout(()=>{throw n},0)}},we=W(P(`${le}/add`),{withTypes:()=>we}),ft=P(`${le}/removeAll`),Pe=W(P(`${le}/remove`),{withTypes:()=>Pe}),qt=(...e)=>{console.error(`${le}/error`,...e)},$t=(e={})=>{let t=new Map,r=new Map,n=f=>{let d=r.get(f)??0;r.set(f,d+1)},a=f=>{let d=r.get(f)??1;d===1?r.delete(f):r.set(f,d-1)},{extra:o,onError:i=qt}=e;ce(i,"onError");let h=f=>(f.unsubscribe=()=>t.delete(f.id),t.set(f.id,f),d=>{f.unsubscribe(),d?.cancelActive&&Re(f)}),s=f=>{let d=dt(t,f)??pt(f);return h(d)};W(s,{withTypes:()=>s});let c=f=>{let d=dt(t,f);return d&&(d.unsubscribe(),f.cancelActive&&Re(d)),!!d};W(c,{withTypes:()=>c});let y=async(f,d,l,u)=>{let p=new AbortController,g=Kt(s,p.signal),T=[];try{f.pending.add(p),n(f),await Promise.resolve(f.effect(d,W({},l,{getOriginalState:u,condition:(m,k)=>g(m,k).then(Boolean),take:g,delay:Ee(p.signal),pause:X(p.signal),extra:o,signal:p.signal,fork:Bt(p.signal,T),unsubscribe:f.unsubscribe,subscribe:()=>{t.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((m,k,R)=>{m!==p&&(m.abort(se),R.delete(m))})},cancel:()=>{p.abort(se),f.pending.delete(p)},throwIfCancelled:()=>{N(p.signal)}})))}catch(m){m instanceof I||ut(i,m,{raisedBy:"effect"})}finally{await Promise.all(T),p.abort(it),a(f),f.pending.delete(p)}},A=Ht(t,r);return{middleware:f=>d=>l=>{if(!B(l))return d(l);if(we.match(l))return s(l.payload);if(ft.match(l)){A();return}if(Pe.match(l))return c(l.payload);let u=f.getState(),p=()=>{if(u===ct)throw new Error(C(23));return u},g;try{if(g=d(l),t.size>0){let T=f.getState(),m=Array.from(t.values());for(let k of m){let R=!1;try{R=k.predicate(l,T,u)}catch(x){R=!1,ut(i,x,{raisedBy:"predicate"})}R&&y(k,l,f,p)}}}finally{u=ct}return g},startListening:s,stopListening:c,clearListeners:A}};var Xt=e=>({middleware:e,applied:new Map}),Jt=e=>t=>t?.meta?.instanceId===e,Qt=()=>{let e=D(),t=new Map,r=Object.assign(P("dynamicMiddleware/add",(...h)=>({payload:h,meta:{instanceId:e}})),{withTypes:()=>r}),n=Object.assign(function(...s){s.forEach(c=>{M(t,c,Xt)})},{withTypes:()=>n}),a=h=>{let s=Array.from(t.values()).map(c=>M(c.applied,h,c.middleware));return V(...s)},o=K(r,Jt(e));return{middleware:h=>s=>c=>o(c)?(n(...c.payload),h.dispatch):a(h)(s)(c),addMiddleware:n,withMiddleware:r,instanceId:e}};import{combineReducers as Yt}from"redux";var Zt=e=>"reducerPath"in e&&typeof e.reducerPath=="string",en=e=>e.flatMap(t=>Zt(t)?[[t.reducerPath,t.reducer]]:Object.entries(t)),Me=Symbol.for("rtk-state-proxy-original"),tn=e=>!!e&&!!e[Me],nn=new WeakMap,rn=(e,t,r)=>M(nn,e,()=>new Proxy(e,{get:(n,a,o)=>{if(a===Me)return n;let i=Reflect.get(n,a,o);if(typeof i>"u"){let h=r[a];if(typeof h<"u")return h;let s=t[a];if(s){let c=s(void 0,{type:D()});if(typeof c>"u")throw new Error(C(24));return r[a]=c,c}}return i}})),an=e=>{if(!tn(e))throw new Error(C(25));return e[Me]},on={},sn=(e=on)=>e;function cn(...e){let t=Object.fromEntries(en(e)),r=()=>Object.keys(t).length?Yt(t):sn,n=r();function a(s,c){return n(s,c)}a.withLazyLoadedSlices=()=>a;let o={},i=(s,c={})=>{let{reducerPath:y,reducer:A}=s,S=t[y];return!c.overrideExisting&&S&&S!==A||(c.overrideExisting&&S!==A&&delete o[y],t[y]=A,n=r()),a},h=Object.assign(function(c,y){return function(S,...f){return c(rn(y?y(S,...f):S,t,o),...f)}},{original:an});return Object.assign(a,{inject:i,selector:h})}function C(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}export{Je as ReducerType,me as SHOULD_AUTOBATCH,I as TaskAbortError,L as Tuple,we as addListener,bt as asyncThunkCreator,Se as autoBatchEnhancer,Qe as buildCreateSlice,ft as clearAllListeners,cn as combineSlices,Et as configureStore,P as createAction,At as createActionCreatorInvariantMiddleware,ge as createAsyncThunk,ye as createDraftSafeSelector,Ie as createDraftSafeSelectorCreator,Qt as createDynamicMiddleware,zt as createEntityAdapter,mt as createImmutableStateInvariantMiddleware,$t as createListenerMiddleware,F as createNextState,ke as createReducer,Ia as createSelector,pe as createSelectorCreator,St as createSerializableStateInvariantMiddleware,Dt as createSlice,G as current,Fe as findNonSerializableValue,C as formatProdErrorMessage,wa as freeze,he as isActionCreator,K as isAllOf,_ as isAnyOf,Ke as isAsyncThunkAction,v as isDraft,Ae as isFluxStandardAction,Be as isFulfilled,Tt as isImmutableDefault,ze as isPending,je as isPlain,te as isRejected,Ge as isRejectedWithValue,va as lruMemoize,qe as miniSerializeError,D as nanoid,Pa as original,Ct as prepareAutoBatched,Pe as removeListener,$e as unwrapResult,fe as weakMapMemoize};
+//# sourceMappingURL=redux-toolkit.browser.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../src/index.ts","../src/immerImports.ts","../src/reselectImports.ts","../src/createDraftSafeSelector.ts","../src/reduxImports.ts","../src/devtoolsExtension.ts","../src/getDefaultMiddleware.ts","../src/tsHelpers.ts","../src/createAction.ts","../src/actionCreatorInvariantMiddleware.ts","../src/utils.ts","../src/immutableStateInvariantMiddleware.ts","../src/serializableStateInvariantMiddleware.ts","../src/autoBatchEnhancer.ts","../src/getDefaultEnhancers.ts","../src/configureStore.ts","../src/mapBuilders.ts","../src/createReducer.ts","../src/matchers.ts","../src/nanoid.ts","../src/createAsyncThunk.ts","../src/createSlice.ts","../src/entities/entity_state.ts","../src/entities/state_selectors.ts","../src/entities/state_adapter.ts","../src/entities/utils.ts","../src/entities/unsorted_state_adapter.ts","../src/entities/sorted_state_adapter.ts","../src/entities/create_adapter.ts","../src/listenerMiddleware/exceptions.ts","../src/listenerMiddleware/utils.ts","../src/listenerMiddleware/task.ts","../src/listenerMiddleware/index.ts","../src/dynamicMiddleware/index.ts","../src/combineSlices.ts","../src/formatProdErrorMessage.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage';\nexport * from 'redux';\nexport { freeze, original } from 'immer';\nexport { createNextState, current, isDraft } from './immerImports';\nexport type { Draft, WritableDraft } from 'immer';\nexport { createSelector, lruMemoize } from 'reselect';\nexport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport type { Selector, OutputSelector } from 'reselect';\nexport { createDraftSafeSelector, createDraftSafeSelectorCreator } from './createDraftSafeSelector';\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';\nexport {\n// js\nconfigureStore } from './configureStore';\nexport type {\n// types\nConfigureStoreOptions, EnhancedStore } from './configureStore';\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension';\nexport {\n// js\ncreateAction, isActionCreator, isFSA as isFluxStandardAction } from './createAction';\nexport type {\n// types\nPayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction } from './createAction';\nexport {\n// js\ncreateReducer } from './createReducer';\nexport type {\n// types\nActions, CaseReducer, CaseReducers } from './createReducer';\nexport {\n// js\ncreateSlice, buildCreateSlice, asyncThunkCreator, ReducerType } from './createSlice';\nexport type {\n// types\nCreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, ReducerCreators, SliceSelectors } from './createSlice';\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nexport {\n// js\ncreateImmutableStateInvariantMiddleware, isImmutableDefault } from './immutableStateInvariantMiddleware';\nexport type {\n// types\nImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\nexport {\n// js\ncreateSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nSerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nActionReducerMapBuilder, AsyncThunkReducers } from './mapBuilders';\nexport { Tuple } from './utils';\nexport { createEntityAdapter } from './entities/create_adapter';\nexport type { EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer } from './entities/models';\nexport { createAsyncThunk, unwrapResult, miniSerializeError } from './createAsyncThunk';\nexport type { AsyncThunk, AsyncThunkConfig, AsyncThunkDispatchConfig, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, GetState, GetThunkAPI, SerializedError, CreateAsyncThunkFunction } from './createAsyncThunk';\nexport {\n// js\nisAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue } from './matchers';\nexport type {\n// types\nActionMatchingAllOf, ActionMatchingAnyOf } from './matchers';\nexport { nanoid } from './nanoid';\nexport type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult } from './listenerMiddleware/index';\nexport type { AnyListenerPredicate } from './listenerMiddleware/types';\nexport { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError } from './listenerMiddleware/index';\nexport type { AddMiddleware, DynamicDispatch, DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './dynamicMiddleware/types';\nexport { createDynamicMiddleware } from './dynamicMiddleware/index';\nexport { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer } from './autoBatchEnhancer';\nexport type { AutoBatchOptions } from './autoBatchEnhancer';\nexport { combineSlices } from './combineSlices';\nexport type { CombinedSliceReducer, WithSlice, WithSlicePreloadedState } from './combineSlices';\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers';\nexport { formatProdErrorMessage } from './formatProdErrorMessage';","export { current, isDraft, produce as createNextState, isDraftable, setUseStrictIteration } from 'immer';","export { createSelectorCreator, weakMapMemoize } from 'reselect';","import { current, isDraft } from './immerImports';\nimport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (...args: unknown[]) => {\n  const createSelector = (createSelectorCreator as any)(...args);\n  const createDraftSafeSelector = Object.assign((...args: unknown[]) => {\n    const selector = createSelector(...args);\n    const wrappedSelector = (value: unknown, ...rest: unknown[]) => selector(isDraft(value) ? current(value) : value, ...rest);\n    Object.assign(wrappedSelector, selector);\n    return wrappedSelector as any;\n  }, {\n    withTypes: () => createDraftSafeSelector\n  });\n  return createDraftSafeSelector;\n};\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector = /* @__PURE__ */\ncreateDraftSafeSelectorCreator(weakMapMemoize);","export { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from 'redux';","import type { Action, ActionCreator, StoreEnhancer } from 'redux';\nimport { compose } from './reduxImports';\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string;\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | {\n    [key: string]: ActionCreator<any>;\n  };\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number;\n  /**\n   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\n   *\n   * @default 50\n   */\n  maxAge?: number;\n  /**\n   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?: boolean | {\n    /**\n     * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n     * - `false` - will handle also circular references.\n     * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n     * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n     *   For each of them you can indicate if to include (by setting as `true`).\n     *   For `function` key you can also specify a custom function which handles serialization.\n     *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n     */\n    options?: undefined | boolean | {\n      date?: true;\n      regex?: true;\n      undefined?: true;\n      error?: true;\n      symbol?: true;\n      map?: true;\n      set?: true;\n      function?: true | ((fn: (...args: any[]) => any) => string);\n    };\n    /**\n     * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\n     * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n     * key. So you can deserialize it back while importing or persisting data.\n     * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\n     */\n    replacer?: (key: string, value: unknown) => any;\n    /**\n     * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n     * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n     * as an example on how to serialize special data types and get them back.\n     */\n    reviver?: (key: string, value: unknown) => any;\n    /**\n     * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n     * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n     * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n     */\n    immutable?: any;\n    /**\n     * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n     */\n    refs?: any;\n  };\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A;\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S;\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[];\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[];\n  /**\n   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean;\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean;\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string;\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean;\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean;\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean;\n  /**\n   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean;\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean;\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean;\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean;\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom';\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom';\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean;\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean;\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean;\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean;\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean;\n  };\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string);\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number;\n}\ntype Compose = typeof compose;\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose;\n  <StoreExt extends {}>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\n  if (arguments.length === 0) return undefined;\n  if (typeof arguments[0] === 'object') return compose;\n  return compose.apply(null, arguments as any as Function[]);\n};\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>;\n} = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION__ : function () {\n  return function (noop) {\n    return noop;\n  };\n};","import type { Middleware, UnknownAction } from 'redux';\nimport type { ThunkMiddleware } from 'redux-thunk';\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk';\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware';\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware';\nimport type { ExcludeFromTuple } from './tsHelpers';\nimport { Tuple } from './utils';\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean';\n}\ninterface ThunkOptions<E = any> {\n  extraArgument: E;\n}\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions;\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;\n}\nexport type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {\n  thunk: false;\n} ? never : O extends {\n  thunk: {\n    extraArgument: infer E;\n  };\n} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;\nexport type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {\n  thunk: true;\n  immutableCheck: true;\n  serializableCheck: true;\n  actionCreatorCheck: true;\n}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;\nexport const buildGetDefaultMiddleware = <S = any,>(): GetDefaultMiddleware<S> => function getDefaultMiddleware(options) {\n  const {\n    thunk = true,\n    immutableCheck = true,\n    serializableCheck = true,\n    actionCreatorCheck = true\n  } = options ?? {};\n  let middlewareArray = new Tuple<Middleware[]>();\n  if (thunk) {\n    if (isBoolean(thunk)) {\n      middlewareArray.push(thunkMiddleware);\n    } else {\n      middlewareArray.push(withExtraArgument(thunk.extraArgument));\n    }\n  }\n  if (process.env.NODE_ENV !== 'production') {\n    if (immutableCheck) {\n      /* PROD_START_REMOVE_UMD */\n      let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(immutableCheck)) {\n        immutableOptions = immutableCheck;\n      }\n      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n      /* PROD_STOP_REMOVE_UMD */\n    }\n    if (serializableCheck) {\n      let serializableOptions: SerializableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(serializableCheck)) {\n        serializableOptions = serializableCheck;\n      }\n      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n    }\n    if (actionCreatorCheck) {\n      let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {};\n      if (!isBoolean(actionCreatorCheck)) {\n        actionCreatorOptions = actionCreatorCheck;\n      }\n      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n    }\n  }\n  return middlewareArray as any;\n};","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport { isAction } from './reduxImports';\nimport type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<P = void, T extends string = string, M = never, E = never> = {\n  payload: P;\n  type: T;\n} & ([M] extends [never] ? {} : {\n  meta: M;\n}) & ([E] extends [never] ? {} : {\n  error: E;\n});\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> = ((...args: any[]) => {\n  payload: P;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  error: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n  error: any;\n});\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {\n  error: infer E;\n} ? E : never, ReturnType<PA> extends {\n  meta: infer M;\n} ? M : never> : void;\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T;\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>;\n};\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>;\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>;\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>;\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>,\n// else\nIsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>,\n// else\nIfVoid<P, ActionCreatorWithoutPayload<T>,\n// else\nIfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>,\n// else\nActionCreatorWithPayload<P, T>>>>>>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args);\n      if (!prepared) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(0) : 'prepareAction did not return an object');\n      }\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && {\n          meta: prepared.meta\n        }),\n        ...('error' in prepared && {\n          error: prepared.error\n        })\n      };\n    }\n    return {\n      type,\n      payload: args[0]\n    };\n  }\n  actionCreator.toString = () => `${type}`;\n  actionCreator.type = type;\n  actionCreator.match = (action: unknown): action is PayloadAction => isAction(action) && action.type === type;\n  return actionCreator;\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function {\n  return typeof action === 'function' && 'type' in action &&\n  // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n  hasMatchFunction(action as any);\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string;\n  payload?: unknown;\n  error?: unknown;\n  meta?: unknown;\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1;\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends ((...args: any[]) => any) ? True : False;","import type { Middleware } from 'redux';\nimport { isActionCreator as isRTKAction } from './createAction';\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & {\n    type?: unknown;\n  };\n}\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : [];\n  const actionName = splitType[splitType.length - 1] || 'actionCreator';\n  return `Detected an action creator with type \"${type || 'unknown'}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nexport function createActionCreatorInvariantMiddleware(options: ActionCreatorInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  }\n  const {\n    isActionCreator = isRTKAction\n  } = options;\n  return () => next => action => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type));\n    }\n    return next(action);\n  };\n}","import { createNextState, isDraftable } from './immerImports';\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0;\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now();\n      try {\n        return fn();\n      } finally {\n        const finished = Date.now();\n        elapsed += finished - started;\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n      }\n    }\n  };\n}\nexport function delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {\n  constructor(length: number);\n  constructor(...items: Items);\n  constructor(...items: any[]) {\n    super(...items);\n    Object.setPrototypeOf(this, Tuple.prototype);\n  }\n  static override get [Symbol.species]() {\n    return Tuple as any;\n  }\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr);\n  }\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this));\n    }\n    return new Tuple(...arr.concat(this));\n  }\n}\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val;\n}\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | PromiseLike<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve: any;\n  let reject: any;\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve,\n    reject\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Middleware } from 'redux';\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware';\nimport { getTimeMeasureUtils } from './utils';\ntype EntryProcessor = (key: string, value: any) => any;\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value);\n}\nexport function trackForMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths | undefined, obj: any) {\n  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);\n    }\n  };\n}\ninterface TrackedProperty {\n  value: any;\n  children: Record<string, any>;\n}\nfunction trackProperties(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], obj: Record<string, any>, path: string = '', checkedObjects: Set<Record<string, any>> = new Set()) {\n  const tracked: Partial<TrackedProperty> = {\n    value: obj\n  };\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj);\n    tracked.children = {};\n    const hasIgnoredPaths = ignoredPaths.length > 0;\n    for (const key in obj) {\n      const nestedPath = path ? path + '.' + key : key;\n      if (hasIgnoredPaths) {\n        const hasMatches = ignoredPaths.some(ignored => {\n          if (ignored instanceof RegExp) {\n            return ignored.test(nestedPath);\n          }\n          return nestedPath === ignored;\n        });\n        if (hasMatches) {\n          continue;\n        }\n      }\n      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);\n    }\n  }\n  return tracked as TrackedProperty;\n}\nfunction detectMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, path: string = ''): {\n  wasMutated: boolean;\n  path?: string;\n} {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined;\n  const sameRef = prevObj === obj;\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return {\n      wasMutated: true,\n      path\n    };\n  }\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return {\n      wasMutated: false\n    };\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {};\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true;\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true;\n  }\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n    if (result.wasMutated) {\n      return result;\n    }\n  }\n  return {\n    wasMutated: false\n  };\n}\ntype IsImmutableFunc = (value: any) => boolean;\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc;\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths;\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number;\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(options: ImmutableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    function stringify(obj: any, serializer?: EntryProcessor, indent?: string | number, decycler?: EntryProcessor): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\n    }\n    function getSerialize(serializer?: EntryProcessor, decycler?: EntryProcessor): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = [];\n      if (!decycler) decycler = function (_: string, value: any) {\n        if (stack[0] === value) return '[Circular ~]';\n        return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n      };\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this);\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value);\n        } else stack.push(value);\n        return serializer == null ? value : serializer.call(this, key, value);\n      };\n    }\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32\n    } = options;\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n    return ({\n      getState\n    }) => {\n      let state = getState();\n      let tracker = track(state);\n      let result;\n      return next => action => {\n        const measureUtils = getTimeMeasureUtils(warnAfter, 'ImmutableStateInvariantMiddleware');\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ''}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        const dispatchedAction = next(action);\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ''}. Take a look at the reducer(s) handling the action ${stringify(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n        return dispatchedAction;\n      };\n    };\n  }\n}","import type { Middleware } from 'redux';\nimport { isAction, isPlainObject } from './reduxImports';\nimport { getTimeMeasureUtils } from './utils';\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val;\n  return val == null || type === 'string' || type === 'boolean' || type === 'number' || Array.isArray(val) || isPlainObject(val);\n}\ninterface NonSerializableValue {\n  keyPath: string;\n  value: unknown;\n}\nexport type IgnorePaths = readonly (string | RegExp)[];\n\n/**\n * @public\n */\nexport function findNonSerializableValue(value: unknown, path: string = '', isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], cache?: WeakSet<object>): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false;\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value\n    };\n  }\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  if (cache?.has(value)) return false;\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue\n      };\n    }\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n      if (foundNestedSerializable) {\n        return foundNestedSerializable;\n      }\n    }\n  }\n  if (cache && isNestedFrozen(value)) cache.add(value);\n  return false;\n}\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false;\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue;\n    if (!isNestedFrozen(nestedValue)) return false;\n  }\n  return true;\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean;\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][];\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[];\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number;\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean;\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean;\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean;\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(options: SerializableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false\n    } = options;\n    const cache: WeakSet<object> | undefined = !disableCache && WeakSet ? new WeakSet() : undefined;\n    return storeAPI => next => action => {\n      if (!isAction(action)) {\n        return next(action);\n      }\n      const result = next(action);\n      const measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type as any) !== -1)) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(action, '', isSerializable, getEntries, ignoredActionPaths, cache);\n          if (foundActionNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundActionNonSerializableValue;\n            console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, '\\nTake a look at the logic that dispatched this action: ', action, '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)');\n          }\n        });\n      }\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState();\n          const foundStateNonSerializableValue = findNonSerializableValue(state, '', isSerializable, getEntries, ignoredPaths, cache);\n          if (foundStateNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundStateNonSerializableValue;\n            console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n      }\n      return result;\n    };\n  }\n}","import type { StoreEnhancer } from 'redux';\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch';\nexport const prepareAutoBatched = <T,>() => (payload: T): {\n  payload: T;\n  meta: unknown;\n} => ({\n  payload,\n  meta: {\n    [SHOULD_AUTOBATCH]: true\n  }\n});\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout);\n  };\n};\nexport type AutoBatchOptions = {\n  type: 'tick';\n} | {\n  type: 'timer';\n  timeout: number;\n} | {\n  type: 'raf';\n} | {\n  type: 'callback';\n  queueNotification: (notify: () => void) => void;\n};\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer = (options: AutoBatchOptions = {\n  type: 'raf'\n}): StoreEnhancer => next => (...args) => {\n  const store = next(...args);\n  let notifying = true;\n  let shouldNotifyAtEndOfTick = false;\n  let notificationQueued = false;\n  const listeners = new Set<() => void>();\n  const queueCallback = options.type === 'tick' ? queueMicrotask : options.type === 'raf' ?\n  // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n  typeof window !== 'undefined' && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === 'callback' ? options.queueNotification : createQueueWithTimer(options.timeout);\n  const notifyListeners = () => {\n    // We're running at the end of the event loop tick.\n    // Run the real listener callbacks to actually update the UI.\n    notificationQueued = false;\n    if (shouldNotifyAtEndOfTick) {\n      shouldNotifyAtEndOfTick = false;\n      listeners.forEach(l => l());\n    }\n  };\n  return Object.assign({}, store, {\n    // Override the base `store.subscribe` method to keep original listeners\n    // from running if we're delaying notifications\n    subscribe(listener: () => void) {\n      // Each wrapped listener will only call the real listener if\n      // the `notifying` flag is currently active when it's called.\n      // This lets the base store work as normal, while the actual UI\n      // update becomes controlled by this enhancer.\n      const wrappedListener: typeof listener = () => notifying && listener();\n      const unsubscribe = store.subscribe(wrappedListener);\n      listeners.add(listener);\n      return () => {\n        unsubscribe();\n        listeners.delete(listener);\n      };\n    },\n    // Override the base `store.dispatch` method so that we can check actions\n    // for the `shouldAutoBatch` flag and determine if batching is active\n    dispatch(action: any) {\n      try {\n        // If the action does _not_ have the `shouldAutoBatch` flag,\n        // we resume/continue normal notify-after-each-dispatch behavior\n        notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n        // If a `notifyListeners` microtask was queued, you can't cancel it.\n        // Instead, we set a flag so that it's a no-op when it does run\n        shouldNotifyAtEndOfTick = !notifying;\n        if (shouldNotifyAtEndOfTick) {\n          // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n          // a microtask to notify listeners at the end of the event loop tick.\n          // Make sure we only enqueue this _once_ per tick.\n          if (!notificationQueued) {\n            notificationQueued = true;\n            queueCallback(notifyListeners);\n          }\n        }\n        // Go ahead and process the action as usual, including reducers.\n        // If normal notification behavior is enabled, the store will notify\n        // all of its own listeners, and the wrapper callbacks above will\n        // see `notifying` is true and pass on to the real listener callbacks.\n        // If we're \"batching\" behavior, then the wrapped callbacks will\n        // bail out, causing the base store notification behavior to be no-ops.\n        return store.dispatch(action);\n      } finally {\n        // Assume we're back to normal behavior after each action\n        notifying = true;\n      }\n    }\n  });\n};","import type { StoreEnhancer } from 'redux';\nimport type { AutoBatchOptions } from './autoBatchEnhancer';\nimport { autoBatchEnhancer } from './autoBatchEnhancer';\nimport { Tuple } from './utils';\nimport type { Middlewares } from './configureStore';\nimport type { ExtractDispatchExtensions } from './tsHelpers';\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions;\n};\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>]>;\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>,>(middlewareEnhancer: StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>): GetDefaultEnhancers<M> => function getDefaultEnhancers(options) {\n  const {\n    autoBatch = true\n  } = options ?? {};\n  let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer);\n  if (autoBatch) {\n    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined));\n  }\n  return enhancerArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Reducer, ReducersMapObject, Middleware, Action, StoreEnhancer, Store, UnknownAction } from 'redux';\nimport { applyMiddleware, createStore, compose, combineReducers, isPlainObject } from './reduxImports';\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';\nimport { composeWithDevTools } from './devtoolsExtension';\nimport type { ThunkMiddlewareFor, GetDefaultMiddleware } from './getDefaultMiddleware';\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware';\nimport type { ExtractDispatchExtensions, ExtractStoreExtensions, ExtractStateExtensions, UnknownIfNonSpecific } from './tsHelpers';\nimport type { Tuple } from './utils';\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers';\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers';\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions;\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean;\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P;\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;\n}\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;\ntype Enhancers = ReadonlyArray<StoreEnhancer>;\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>, StoreEnhancer]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>();\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined\n  } = options || {};\n  let rootReducer: Reducer<S, A, P>;\n  if (typeof reducer === 'function') {\n    rootReducer = reducer;\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>;\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(1) : '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\n  }\n  if (process.env.NODE_ENV !== 'production' && middleware && typeof middleware !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(2) : '`middleware` field must be a callback');\n  }\n  let finalMiddleware: Tuple<Middlewares<S>>;\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware);\n    if (process.env.NODE_ENV !== 'production' && !Array.isArray(finalMiddleware)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(3) : 'when using a middleware builder function, an array of middleware must be returned');\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware();\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(4) : 'each middleware provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>();\n    finalMiddleware.forEach(middleware => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(42) : 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.');\n      }\n      middlewareReferences.add(middleware);\n    });\n  }\n  let finalCompose = compose;\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools)\n    });\n  }\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer);\n  if (process.env.NODE_ENV !== 'production' && enhancers && typeof enhancers !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(5) : '`enhancers` field must be a callback');\n  }\n  let storeEnhancers = typeof enhancers === 'function' ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(6) : '`enhancers` callback must return an array');\n  }\n  if (process.env.NODE_ENV !== 'production' && storeEnhancers.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(7) : 'each enhancer provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n    console.error('middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`');\n  }\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers);\n  return createStore(rootReducer, preloadedState as P, composedEnhancer);\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7 } from \"@reduxjs/toolkit\";\nimport type { Action } from 'redux';\nimport type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';\nimport type { TypeGuard } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk';\nexport type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;\n  rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;\n  fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;\n  settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;\n};\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>;\n  type: Type;\n};\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;\n\n  /**\n   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.\n   * @remarks\n   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param asyncThunk - The async thunk action creator itself.\n   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.\n   * @example\n  ```ts no-transpile\n  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'\n  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {\n  const response = await fetch(`https://reqres.in/api/users/${id}`)\n  return (await response.json()).data\n  })\n  const reducer = createReducer(initialState, (builder) => {\n  builder.addAsyncThunk(fetchUserById, {\n    pending: (state, action) => {\n      state.fetchUserById.loading = 'pending'\n    },\n    fulfilled: (state, action) => {\n      state.fetchUserById.data = action.payload\n    },\n    rejected: (state, action) => {\n      state.fetchUserById.error = action.error\n    },\n    settled: (state, action) => {\n      state.fetchUserById.loading = action.meta.requestStatus\n    },\n  })\n  })\n   */\n  addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n  ```ts\n  import {\n  createAction,\n  createReducer,\n  AsyncThunk,\n  UnknownAction,\n  } from \"@reduxjs/toolkit\";\n  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n  type PendingAction = ReturnType<GenericAsyncThunk[\"pending\"]>;\n  type RejectedAction = ReturnType<GenericAsyncThunk[\"rejected\"]>;\n  type FulfilledAction = ReturnType<GenericAsyncThunk[\"fulfilled\"]>;\n  const initialState: Record<string, string> = {};\n  const resetAction = createAction(\"reset-tracked-loading-state\");\n  function isPendingAction(action: UnknownAction): action is PendingAction {\n  return typeof action.type === \"string\" && action.type.endsWith(\"/pending\");\n  }\n  const reducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(resetAction, () => initialState)\n    // matcher can be defined outside as a type predicate function\n    .addMatcher(isPendingAction, (state, action) => {\n      state[action.meta.requestId] = \"pending\";\n    })\n    .addMatcher(\n      // matcher can be defined inline as a type predicate function\n      (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"rejected\";\n      }\n    )\n    // matcher can just return boolean and the matcher can receive a generic argument\n    .addMatcher<FulfilledAction>(\n      (action) => action.type.endsWith(\"/fulfilled\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"fulfilled\";\n      }\n    );\n  });\n  ```\n   */\n  addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n  ```ts\n  import { createReducer } from '@reduxjs/toolkit'\n  const initialState = { otherActions: 0 }\n  const reducer = createReducer(initialState, builder => {\n  builder\n    // .addCase(...)\n    // .addMatcher(...)\n    .addDefaultCase((state, action) => {\n      state.otherActions++\n    })\n  })\n  ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {};\n}\nexport function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [CaseReducers<S, any>, ActionMatcherDescriptionCollection<S>, CaseReducer<S, Action> | undefined] {\n  const actionsMap: CaseReducers<S, any> = {};\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = [];\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined;\n  const builder = {\n    addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<S>) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(26) : '`builder.addCase` should only be called before calling `builder.addMatcher`');\n        }\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(27) : '`builder.addCase` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n      if (!type) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(28) : '`builder.addCase` cannot be called with an empty action type');\n      }\n      if (type in actionsMap) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(29) : '`builder.addCase` cannot be called with two reducers for the same action type ' + `'${type}'`);\n      }\n      actionsMap[type] = reducer;\n      return builder;\n    },\n    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>) {\n      if (process.env.NODE_ENV !== 'production') {\n        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(43) : '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;\n      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;\n      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;\n      if (reducers.settled) actionMatchers.push({\n        matcher: asyncThunk.settled,\n        reducer: reducers.settled\n      });\n      return builder;\n    },\n    addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<S, A extends Action ? A : A & Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(30) : '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      actionMatchers.push({\n        matcher,\n        reducer\n      });\n      return builder;\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(31) : '`builder.addDefaultCase` can only be called once');\n        }\n      }\n      defaultCaseReducer = reducer;\n      return builder;\n    }\n  };\n  builderCallback(builder);\n  return [actionsMap, actionMatchers, defaultCaseReducer];\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Draft } from 'immer';\nimport { createNextState, isDraft, isDraftable, setUseStrictIteration } from './immerImports';\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { ActionReducerMapBuilder } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { NoInfer, TypeGuard } from './tsHelpers';\nimport { freezeDraftable } from './utils';\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>;\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>;\n  reducer: CaseReducer<S, NoInfer<A>>;\n};\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;\nexport type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void };\nexport type NotFunction<T> = T extends Function ? never : T;\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function';\n}\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S;\n};\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n```ts\nimport {\n  createAction,\n  createReducer,\n  UnknownAction,\n  PayloadAction,\n} from \"@reduxjs/toolkit\";\n\nconst increment = createAction<number>(\"increment\");\nconst decrement = createAction<number>(\"decrement\");\n\nfunction isActionWithNumberPayload(\n  action: UnknownAction\n): action is PayloadAction<number> {\n  return typeof action.payload === \"number\";\n}\n\nconst reducer = createReducer(\n  {\n    counter: 0,\n    sumOfNumberPayloads: 0,\n    unhandledActions: 0,\n  },\n  (builder) => {\n    builder\n      .addCase(increment, (state, action) => {\n        // action is inferred correctly here\n        state.counter += action.payload;\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {\n        state.counter -= action.payload;\n      })\n      // You can apply a \"matcher function\" to incoming actions\n      .addMatcher(isActionWithNumberPayload, (state, action) => {})\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {});\n  }\n);\n```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n    }\n  }\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S;\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState());\n  } else {\n    const frozenInitialState = freezeDraftable(initialState);\n    getInitialState = () => frozenInitialState;\n  }\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n      matcher\n    }) => matcher(action)).map(({\n      reducer\n    }) => reducer)];\n    if (caseReducers.filter(cr => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer];\n    }\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S>; // We can assume this is already a draft\n          const result = caseReducer(draft, action);\n          if (result === undefined) {\n            return previousState;\n          }\n          return result as S;\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action);\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState;\n            }\n            throw Error('A case reducer on a non-draftable value must not return undefined');\n          }\n          return result as S;\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action);\n          });\n        }\n      }\n      return previousState;\n    }, state);\n  }\n  reducer.getInitialState = getInitialState;\n  return reducer as ReducerWithInitialState<S>;\n}","import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action);\n  } else {\n    return matcher(action);\n  }\n};\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]) {\n  if (!action || !action.meta) return false;\n  const hasValidRequestId = typeof action.meta.requestId === 'string';\n  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n  return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return typeof a[0] === 'function' && 'pending' in a[0] && 'fulfilled' in a[0] && 'rejected' in a[0];\n}\nexport type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction;\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.pending));\n}\nexport type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.rejected));\n}\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {\n  rejectValue: infer RejectedValue;\n}> ? {\n  payload: RejectedValue;\n} : unknown);\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue;\n  };\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0]);\n  }\n  return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.fulfilled));\n}\nexport type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;\nexport type AnyAsyncThunk = {\n  pending: {\n    match: (action: any) => action is any;\n  };\n  fulfilled: {\n    match: (action: any) => action is any;\n  };\n  rejected: {\n    match: (action: any) => action is any;\n  };\n};\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}","// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\n/**\n *\n * @public\n */\nexport let nanoid = (size = 21) => {\n  let id = '';\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size;\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[Math.random() * 64 | 0];\n  }\n  return id;\n};","import type { Dispatch, UnknownAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport type { ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport { isAnyOf } from './matchers';\nimport { nanoid } from './nanoid';\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown, SafePromise } from './tsHelpers';\nexport type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {\n  dispatch: D;\n  getState: () => S;\n  extra: E;\n  requestId: string;\n  signal: AbortSignal;\n  abort: (reason?: string) => void;\n  rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;\n  fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;\n};\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string;\n  message?: string;\n  stack?: string;\n  code?: string;\n}\nconst commonProperties: Array<keyof SerializedError> = ['name', 'message', 'stack', 'code'];\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue';\n  constructor(public readonly payload: Payload, public readonly meta: RejectedMeta) {}\n}\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta';\n  constructor(public readonly payload: Payload, public readonly meta: FulfilledMeta) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {};\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property];\n      }\n    }\n    return simpleError;\n  }\n  return {\n    message: String(value)\n  };\n};\nexport type AsyncThunkConfig = {\n  state?: unknown;\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;\n  extra?: unknown;\n  rejectValue?: unknown;\n  serializedErrorType?: unknown;\n  pendingMeta?: unknown;\n  fulfilledMeta?: unknown;\n  rejectedMeta?: unknown;\n};\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State;\n} ? State : unknown;\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends {\n  extra: infer Extra;\n} ? Extra : unknown;\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch;\n} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue;\n} ? RejectValue : unknown;\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta;\n} ? PendingMeta : unknown;\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta;\n} ? FulfilledMeta : unknown;\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta;\n} ? RejectedMeta : unknown;\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType;\n} ? GetSerializedErrorType : SerializedError;\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {\n  abort: (reason?: string) => void;\n  requestId: string;\n  arg: ThunkArg;\n  unwrap: () => Promise<Returned>;\n};\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal;\n}\ntype AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg,\n// any handling\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// unknown handling\nunknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n: [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n: [void] extends [ThunkArg] // make optional\n? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n: [undefined] extends [ThunkArg] ? WithStrictNullChecks<\n// with strict nullChecks: make optional\n(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// without strict null checks this will match everything, so don't make it optional\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> // default case: normal argument\n: (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean;\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string;\n} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   *\n   * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n   * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n   */\n  getPendingMeta?(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   */\n  getPendingMeta(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}>;\nexport type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?], undefined, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'pending';\n} & GetPendingMeta<ThunkApiConfig>>;\nexport type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Error | null, string, ThunkArg, GetRejectValue<ThunkApiConfig>?, GetRejectedMeta<ThunkApiConfig>?], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'rejected';\n  aborted: boolean;\n  condition: boolean;\n} & (({\n  rejectedWithValue: false;\n} & { [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined }) | ({\n  rejectedWithValue: true;\n} & GetRejectedMeta<ThunkApiConfig>))>;\nexport type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?], Returned, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'fulfilled';\n} & GetFulfilledMeta<ThunkApiConfig>>;\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;\n  fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;\n  // matchSettled?\n  settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;\n  typePrefix: string;\n};\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;\nexport type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n  withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\nconst externalAbortMessage = 'External signal was aborted';\nexport const createAsyncThunk = /* @__PURE__ */(() => {\n  function createAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>;\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>;\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>;\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>;\n    const fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/fulfilled', (payload: Returned, requestId: string, arg: ThunkArg, meta?: FulfilledMeta) => ({\n      payload,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'fulfilled' as const\n      }\n    }));\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/pending', (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n      payload: undefined,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'pending' as const\n      }\n    }));\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/rejected', (error: Error | null, requestId: string, arg: ThunkArg, payload?: RejectedValue, meta?: RejectedMeta) => ({\n      payload,\n      error: (options && options.serializeError || miniSerializeError)(error || 'Rejected') as GetSerializedErrorType<ThunkApiConfig>,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        rejectedWithValue: !!payload,\n        requestStatus: 'rejected' as const,\n        aborted: error?.name === 'AbortError',\n        condition: error?.name === 'ConditionError'\n      }\n    }));\n    function actionCreator(arg: ThunkArg, {\n      signal\n    }: AsyncThunkDispatchConfig = {}): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n        const abortController = new AbortController();\n        let abortHandler: (() => void) | undefined;\n        let abortReason: string | undefined;\n        function abort(reason?: string) {\n          abortReason = reason;\n          abortController.abort();\n        }\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage);\n          } else {\n            signal.addEventListener('abort', () => abort(externalAbortMessage), {\n              once: true\n            });\n          }\n        }\n        const promise = async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>;\n          try {\n            let conditionResult = options?.condition?.(arg, {\n              getState,\n              extra\n            });\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult;\n            }\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.'\n              };\n            }\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted'\n                });\n              };\n              abortController.signal.addEventListener('abort', abortHandler, {\n                once: true\n              });\n            });\n            dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n              requestId,\n              arg\n            }, {\n              getState,\n              extra\n            })) as any);\n            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n              dispatch,\n              getState,\n              extra,\n              requestId,\n              signal: abortController.signal,\n              abort,\n              rejectWithValue: ((value: RejectedValue, meta?: RejectedMeta) => {\n                return new RejectWithValue(value, meta);\n              }) as any,\n              fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                return new FulfillWithMeta(value, meta);\n              }) as any\n            })).then(result => {\n              if (result instanceof RejectWithValue) {\n                throw result;\n              }\n              if (result instanceof FulfillWithMeta) {\n                return fulfilled(result.payload, requestId, arg, result.meta);\n              }\n              return fulfilled(result as any, requestId, arg);\n            })]);\n          } catch (err) {\n            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err as any, requestId, arg);\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler);\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && (finalAction as any).meta.condition;\n          if (!skipDispatch) {\n            dispatch(finalAction as any);\n          }\n          return finalAction;\n        }();\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult);\n          }\n        });\n      };\n    }\n    return Object.assign(actionCreator as AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig>, {\n      pending,\n      rejected,\n      fulfilled,\n      settled: isAnyOf(rejected, fulfilled),\n      typePrefix\n    });\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk;\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>;\n})();\ninterface UnwrappableAction {\n  payload: any;\n  meta?: any;\n  error?: any;\n}\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {\n  error: any;\n}>['payload'];\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload;\n  }\n  if (action.error) {\n    throw action.error;\n  }\n  return action.payload;\n}\ntype WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return value !== null && typeof value === 'object' && typeof value.then === 'function';\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { Selector } from 'reselect';\nimport type { InjectConfig } from './combineSlices';\nimport type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport type { AsyncThunk, AsyncThunkConfig, AsyncThunkOptions, AsyncThunkPayloadCreator, OverrideThunkApiConfigs } from './createAsyncThunk';\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk';\nimport type { ActionMatcherDescriptionCollection, CaseReducer, ReducerWithInitialState } from './createReducer';\nimport { createReducer } from './createReducer';\nimport type { ActionReducerMapBuilder, AsyncThunkReducers, TypedActionCreator } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { Id, TypeGuard } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\nconst asyncThunkSymbol = /* @__PURE__ */Symbol.for('rtk-slice-createasyncthunk');\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk;\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk\n};\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath;\n};\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice name.\n   */\n  name: Name;\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath;\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>;\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>;\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>;\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State;\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>>;\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {\n    inject: (slice: {\n      reducerPath: string;\n      reducer: Reducer;\n    }, config?: InjectConfig) => void;\n  }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State;\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]?: State | undefined }>>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State;\n};\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name;\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath;\n\n  /**\n   * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n   */\n  initialState: State | (() => State);\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n  ```ts\n  import { createAction, createSlice, Action } from '@reduxjs/toolkit'\n  const incrementBy = createAction<number>('incrementBy')\n  const decrement = createAction('decrement')\n  interface RejectedAction extends Action {\n  error: Error\n  }\n  function isRejectedAction(action: Action): action is RejectedAction {\n  return action.type.endsWith('rejected')\n  }\n  createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {},\n  extraReducers: builder => {\n    builder\n      .addCase(incrementBy, (state, action) => {\n        // action is inferred correctly here if using TS\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {})\n      // You can match a range of action types\n      .addMatcher(\n        isRejectedAction,\n        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n        (state, action) => {}\n      )\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {})\n    }\n  })\n  ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors;\n}\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T;\n};\nexport type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>;\n  prepare: PrepareAction<Action['payload']>;\n};\nexport interface CaseReducerWithPrepareDefinition<State, Action extends PayloadAction> extends CaseReducerWithPrepare<State, Action>, ReducerDefinition<ReducerType.reducerWithPrepare> {}\ntype AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;\n};\ntype AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;\n};\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = { [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K] };\ninterface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {\n  <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;\n  <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;\n  withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n}\nexport interface ReducerCreators<State> {\n  reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;\n  reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;\n  asyncThunk: AsyncThunkCreator<State>;\n  preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare;\n    prepare: Prepare;\n    reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;\n  };\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any;\n};\ntype SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {\n  prepare: any;\n} ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {\n  reducer: any;\n} ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never };\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<CR extends {\n  prepare: any;\n}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ((state: any, action: infer Action) => any) ? Action extends {\n  payload: infer P;\n} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {\n  reducer: infer Reducer;\n} ? Reducer : Definition : never };\ntype RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {\n  unwrapped: S;\n} : never;\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState> };\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends {\n  reducer(s: S, action?: infer A): any;\n} ? {\n  prepare(...a: never[]): Omit<A, 'type'>;\n} : {} };\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`;\n}\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator;\n  };\n}\nexport function buildCreateSlice({\n  creators\n}: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n  return function createSlice<State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {\n    const {\n      name,\n      reducerPath = name as unknown as ReducerPath\n    } = options;\n    if (!name) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(11) : '`name` is a required option for createSlice');\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (options.initialState === undefined) {\n        console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`');\n      }\n    }\n    const reducers = (typeof options.reducers === 'function' ? options.reducers(buildReducerCreators<State>()) : options.reducers) || {};\n    const reducerNames = Object.keys(reducers);\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: []\n    };\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<State>) {\n        const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n        if (!type) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(12) : '`context.addCase` cannot be called with an empty action type');\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(13) : '`context.addCase` cannot be called with two reducers for the same action type: ' + type);\n        }\n        context.sliceCaseReducersByType[type] = reducer;\n        return contextMethods;\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({\n          matcher,\n          reducer\n        });\n        return contextMethods;\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator;\n        return contextMethods;\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer;\n        return contextMethods;\n      }\n    };\n    reducerNames.forEach(reducerName => {\n      const reducerDefinition = reducers[reducerName];\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function'\n      };\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n      } else {\n        handleNormalReducerDefinition<State>(reducerDetails, reducerDefinition as any, contextMethods);\n      }\n    });\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n        }\n      }\n      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = undefined] = typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType\n      };\n      return createReducer(options.initialState, builder => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>);\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer);\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer);\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer);\n        }\n      });\n    }\n    const selectSelf = (state: State) => state;\n    const injectedSelectorCache = new Map<boolean, WeakMap<(rootState: any) => State | undefined, Record<string, (rootState: any) => any>>>();\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>();\n    let _reducer: ReducerWithInitialState<State>;\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer(state, action);\n    }\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer.getInitialState();\n    }\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(reducerPath: CurrentReducerPath, injected = false): Pick<Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'> {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath];\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(15) : 'selectSlice returned undefined for an uninjected slice reducer');\n          }\n        }\n        return sliceState;\n      }\n      function getSelectors(selectState: (rootState: any) => State = selectSelf) {\n        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => new WeakMap());\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {};\n          for (const [name, selector] of Object.entries(options.selectors ?? {})) {\n            map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);\n          }\n          return map;\n        }) as any;\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice);\n        },\n        selectSlice\n      };\n    }\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, {\n        reducerPath: pathOpt,\n        ...config\n      } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath;\n        injectable.inject({\n          reducerPath: newReducerPath,\n          reducer\n        }, config);\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true)\n        } as any;\n      }\n    };\n    return slice;\n  };\n}\nfunction wrapSelector<State, NewState, S extends Selector<State>>(selector: S, selectState: Selector<NewState, State>, getInitialState: () => State, injected?: boolean) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState);\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState();\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(16) : 'selectState returned undefined for an uninjected slice reducer');\n      }\n    }\n    return selector(sliceState, ...args);\n  }\n  wrapper.unwrapped = selector;\n  return wrapper as RemappedSelector<S, NewState>;\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */buildCreateSlice();\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<string, CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>>;\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>;\n  sliceMatchers: ActionMatcherDescriptionCollection<State>;\n  actionCreators: Record<string, Function>;\n}\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ReducerHandlingContextMethods<State>;\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ReducerHandlingContextMethods<State>;\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<State, A extends Action ? A : A & Action>): ReducerHandlingContextMethods<State>;\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * context.exposeAction(\"addPost\", createAction<Post>(\"addPost\"));\n   *\n   * export const { addPost } = slice.actions\n   *\n   * dispatch(addPost(post))\n   */\n  exposeAction(name: string, actionCreator: Function): ReducerHandlingContextMethods<State>;\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * context.exposeCaseReducer(\"addPost\", (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload)\n   * })\n   *\n   * slice.caseReducers.addPost([], addPost(post))\n   */\n  exposeCaseReducer(name: string, reducer: CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>): ReducerHandlingContextMethods<State>;\n}\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string;\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string;\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean;\n}\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(payloadCreator: AsyncThunkPayloadCreator<any, any>, config: AsyncThunkSliceReducerConfig<State, any>): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config\n    };\n  }\n  asyncThunk.withTypes = () => asyncThunk;\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign({\n        // hack so the wrapping function has the same name as the original\n        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n        [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n          return caseReducer(...args);\n        }\n      }[caseReducer.name], {\n        _reducerDefinitionType: ReducerType.reducer\n      } as const);\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer\n      };\n    },\n    asyncThunk: asyncThunk as any\n  };\n}\nfunction handleNormalReducerDefinition<State>({\n  type,\n  reducerName,\n  createNotation\n}: ReducerDetails, maybeReducerWithPrepare: CaseReducer<State, {\n  payload: any;\n  type: string;\n}> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, context: ReducerHandlingContextMethods<State>) {\n  let caseReducer: CaseReducer<State, any>;\n  let prepareCallback: PrepareAction<any> | undefined;\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(17) : 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.');\n    }\n    caseReducer = maybeReducerWithPrepare.reducer;\n    prepareCallback = maybeReducerWithPrepare.prepare;\n  } else {\n    caseReducer = maybeReducerWithPrepare;\n  }\n  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition<State>(reducerDefinition: any): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk;\n}\nfunction isCaseReducerWithPrepareDefinition<State>(reducerDefinition: any): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare;\n}\nfunction handleThunkCaseReducerDefinition<State>({\n  type,\n  reducerName\n}: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, context: ReducerHandlingContextMethods<State>, cAT: typeof _createAsyncThunk | undefined) {\n  if (!cAT) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(18) : 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.');\n  }\n  const {\n    payloadCreator,\n    fulfilled,\n    pending,\n    rejected,\n    settled,\n    options\n  } = reducerDefinition;\n  const thunk = cAT(type, payloadCreator, options as any);\n  context.exposeAction(reducerName, thunk);\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled);\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending);\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected);\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled);\n  }\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop\n  });\n}\nfunction noop() {}","import type { EntityId, EntityState, EntityStateAdapter, EntityStateFactory } from './models';\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<T, Id> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>\n  };\n}\nexport function createInitialStateFactory<T, Id extends EntityId>(stateAdapter: EntityStateAdapter<T, Id>): EntityStateFactory<T, Id> {\n  function getInitialState(state?: undefined, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id>;\n  function getInitialState<S extends object>(additionalState: S, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id> & S;\n  function getInitialState(additionalState: any = {}, entities?: readonly T[] | Record<Id, T>): any {\n    const state = Object.assign(getInitialEntityState(), additionalState);\n    return entities ? stateAdapter.setAll(state, entities) : state;\n  }\n  return {\n    getInitialState\n  };\n}","import type { CreateSelectorFunction, Selector } from 'reselect';\nimport { createDraftSafeSelector } from '../createDraftSafeSelector';\nimport type { EntityId, EntitySelectors, EntityState } from './models';\ntype AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction;\n};\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;\n  function getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;\n  function getSelectors<V>(selectState?: (state: V) => EntityState<T, Id>, options: GetSelectorsOptions = {}): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction\n    } = options;\n    const selectIds = (state: EntityState<T, Id>) => state.ids;\n    const selectEntities = (state: EntityState<T, Id>) => state.entities;\n    const selectAll = createSelector(selectIds, selectEntities, (ids, entities): T[] => ids.map(id => entities[id]!));\n    const selectId = (_: unknown, id: Id) => id;\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id];\n    const selectTotal = createSelector(selectIds, ids => ids.length);\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById)\n      };\n    }\n    const selectGlobalizedEntities = createSelector(selectState as Selector<V, EntityState<T, Id>>, selectEntities);\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(selectGlobalizedEntities, selectId, selectById)\n    };\n  }\n  return {\n    getSelectors\n  };\n}","import { createNextState, isDraft } from '../immerImports';\nimport type { Draft } from 'immer';\nimport type { EntityId, DraftableEntityState, PreventAny } from './models';\nimport type { PayloadAction } from '../createAction';\nimport { isFSA } from '../createAction';\nexport const isDraftTyped = isDraft as <T>(value: T | Draft<T>) => value is Draft<T>;\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(mutator: (state: DraftableEntityState<T, Id>) => void) {\n  const operator = createStateOperator((_: undefined, state: DraftableEntityState<T, Id>) => mutator(state));\n  return function operation<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S {\n    return operator(state as S, undefined);\n  };\n}\nexport function createStateOperator<T, Id extends EntityId, R>(mutator: (arg: R, state: DraftableEntityState<T, Id>) => void) {\n  return function operation<S extends DraftableEntityState<T, Id>>(state: S, arg: R | PayloadAction<R>): S {\n    function isPayloadActionArgument(arg: R | PayloadAction<R>): arg is PayloadAction<R> {\n      return isFSA(arg);\n    }\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft);\n      } else {\n        mutator(arg, draft);\n      }\n    };\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state);\n\n      // since it's a draft, we'll just return it\n      return state;\n    }\n    return createNextState(state, runMutator);\n  };\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../immerImports';\nimport type { DraftableEntityState, EntityId, IdSelector, Update } from './models';\nexport function selectIdValue<T, Id extends EntityId>(entity: T, selectId: IdSelector<T, Id>) {\n  const key = selectId(entity);\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    console.warn('The entity passed to the `selectId` implementation returned undefined.', 'You should probably provide your own `selectId` implementation.', 'The entity that was passed:', entity, 'The `selectId` implementation:', selectId.toString());\n  }\n  return key;\n}\nexport function ensureEntitiesArray<T, Id extends EntityId>(entities: readonly T[] | Record<Id, T>): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities);\n  }\n  return entities;\n}\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}\nexport function splitAddedUpdatedEntities<T, Id extends EntityId>(newEntities: readonly T[] | Record<Id, T>, selectId: IdSelector<T, Id>, state: DraftableEntityState<T, Id>): [T[], Update<T, Id>[], Id[]] {\n  newEntities = ensureEntitiesArray(newEntities);\n  const existingIdsArray = getCurrent(state.ids);\n  const existingIds = new Set<Id>(existingIdsArray);\n  const added: T[] = [];\n  const addedIds = new Set<Id>([]);\n  const updated: Update<T, Id>[] = [];\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId);\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({\n        id,\n        changes: entity\n      });\n    } else {\n      addedIds.add(id);\n      added.push(entity);\n    }\n  }\n  return [added, updated, existingIdsArray];\n}","import type { Draft } from 'immer';\nimport type { EntityStateAdapter, IdSelector, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator, createSingleArgumentStateOperator } from './state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities } from './utils';\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (key in state.entities) {\n      return;\n    }\n    state.ids.push(key as Id & Draft<Id>);\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      addOneMutably(entity, state);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>);\n    }\n    ;\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      setOneMutably(entity, state);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.ids = [];\n    state.entities = {} as Record<Id, T>;\n    addManyMutably(newEntities, state);\n  }\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state);\n  }\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false;\n    keys.forEach(key => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key];\n        didMutate = true;\n      }\n    });\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter(id => id in state.entities) as Id[] | Draft<Id[]>;\n    }\n  }\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {}\n    });\n  }\n  function takeNewKey(keys: {\n    [id: string]: Id;\n  }, update: Update<T, Id>, state: R): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id];\n    if (original === undefined) {\n      return false;\n    }\n    const updated: T = Object.assign({}, original, update.changes);\n    const newKey = selectIdValue(updated, selectId);\n    const hasNewKey = newKey !== update.id;\n    if (hasNewKey) {\n      keys[update.id] = newKey;\n      delete (state.entities as Record<Id, T>)[update.id];\n    }\n    ;\n    (state.entities as Record<Id, T>)[newKey] = updated;\n    return hasNewKey;\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    const newKeys: {\n      [id: string]: Id;\n    } = {};\n    const updatesPerEntity: {\n      [id: string]: Update<T, Id>;\n    } = {};\n    updates.forEach(update => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes\n          }\n        };\n      }\n    });\n    updates = Object.values(updatesPerEntity);\n    const didMutateEntities = updates.length > 0;\n    if (didMutateEntities) {\n      const didMutateIds = updates.filter(update => takeNewKey(newKeys, update, state)).length > 0;\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map(e => selectIdValue(e as T, selectId));\n      }\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    addManyMutably(added, state);\n    updateManyMutably(updated, state);\n  }\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably)\n  };\n}","import type { IdSelector, Comparer, EntityStateAdapter, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator } from './state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities, getCurrent } from './utils';\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): number {\n  let lowIndex = 0;\n  let highIndex = sortedItems.length;\n  while (lowIndex < highIndex) {\n    let middleIndex = lowIndex + highIndex >>> 1;\n    const currentItem = sortedItems[middleIndex];\n    const res = comparisonFunction(item, currentItem);\n    if (res >= 0) {\n      lowIndex = middleIndex + 1;\n    } else {\n      highIndex = middleIndex;\n    }\n  }\n  return lowIndex;\n}\nexport function insert<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n  sortedItems.splice(insertAtIndex, 0, item);\n  return sortedItems;\n}\nexport function createSortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>, comparer: Comparer<T>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  const {\n    removeOne,\n    removeMany,\n    removeAll\n  } = createUnsortedStateAdapter(selectId);\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state);\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R, existingIds?: Id[]): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids));\n    const addedKeys = new Set<Id>();\n    const models = newEntities.filter(model => {\n      const modelId = selectIdValue(model, selectId);\n      const notAdded = !addedKeys.has(modelId);\n      if (notAdded) addedKeys.add(modelId);\n      return !existingKeys.has(modelId) && notAdded;\n    });\n    if (models.length !== 0) {\n      mergeFunction(state, models);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state);\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    let deduplicatedEntities = {} as Record<Id, T>;\n    newEntities = ensureEntitiesArray(newEntities);\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        const entityId = selectId(item);\n        // For multiple items with the same ID, we should keep the last one.\n        deduplicatedEntities[entityId] = item;\n        delete (state.entities as Record<Id, T>)[entityId];\n      }\n      newEntities = ensureEntitiesArray(deduplicatedEntities);\n      mergeFunction(state, newEntities);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.entities = {} as Record<Id, T>;\n    state.ids = [];\n    addManyMutably(newEntities, state, []);\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    let appliedUpdates = false;\n    let replacedIds = false;\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id];\n      if (!entity) {\n        continue;\n      }\n      appliedUpdates = true;\n      Object.assign(entity, update.changes);\n      const newId = selectId(entity);\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true;\n        delete (state.entities as Record<Id, T>)[update.id];\n        const oldIndex = (state.ids as Id[]).indexOf(update.id);\n        state.ids[oldIndex] = newId;\n        (state.entities as Record<Id, T>)[newId] = entity;\n      }\n    }\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds);\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray);\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state);\n    }\n  }\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue;\n      }\n      return false;\n    }\n    return true;\n  }\n  type MergeFunction = (state: R, addedItems: readonly T[], appliedUpdates?: boolean, replacedIds?: boolean) => void;\n  const mergeFunction: MergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n    const currentEntities = getCurrent(state.entities);\n    const currentIds = getCurrent(state.ids);\n    const stateEntities = state.entities as Record<Id, T>;\n    let ids: Iterable<Id> = currentIds;\n    if (replacedIds) {\n      ids = new Set(currentIds);\n    }\n    let sortedEntities: T[] = [];\n    for (const id of ids) {\n      const entity = currentEntities[id];\n      if (entity) {\n        sortedEntities.push(entity);\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0;\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item;\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer);\n      }\n    }\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer);\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer);\n    }\n    const newSortedIds = sortedEntities.map(selectId);\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds;\n    }\n  };\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably)\n  };\n}","import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models';\nimport { createInitialStateFactory } from './entity_state';\nimport { createSelectorsFactory } from './state_selectors';\nimport { createSortedStateAdapter } from './sorted_state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport type { WithRequiredProp } from '../tsHelpers';\nexport function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;\nexport function createEntityAdapter<T extends {\n  id: EntityId;\n}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(options: EntityAdapterOptions<T, EntityId> = {}): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options\n  };\n  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n  const stateFactory = createInitialStateFactory(stateAdapter);\n  const selectorsFactory = createSelectorsFactory<T, EntityId>();\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter\n  };\n}","import type { SerializedError } from '@reduxjs/toolkit';\nconst task = 'task';\nconst listener = 'listener';\nconst completed = 'completed';\nconst cancelled = 'cancelled';\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const;\nexport const taskCompleted = `task-${completed}` as const;\nexport const listenerCancelled = `${listener}-${cancelled}` as const;\nexport const listenerCompleted = `${listener}-${completed}` as const;\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError';\n  message: string;\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nexport const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown = (func: unknown, expected: string) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(32) : `${expected} is not a function`);\n  }\n};\nexport const noop = () => {};\nexport const catchRejection = <T,>(promise: Promise<T>, onError = noop): Promise<T> => {\n  promise.catch(onError);\n  return promise;\n};\nexport const addAbortSignalListener = (abortSignal: AbortSignal, callback: (evt: Event) => void) => {\n  abortSignal.addEventListener('abort', callback, {\n    once: true\n  });\n  return () => abortSignal.removeEventListener('abort', callback);\n};","import { TaskAbortError } from './exceptions';\nimport type { TaskResult } from './types';\nimport { addAbortSignalListener, catchRejection, noop } from './utils';\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @see {TaskAbortError}\n * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    throw new TaskAbortError(signal.reason);\n  }\n};\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(signal: AbortSignal, promise: Promise<T>): Promise<T> {\n  let cleanup = noop;\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n    if (signal.aborted) {\n      notifyRejection();\n      return;\n    }\n    cleanup = addAbortSignalListener(signal, notifyRejection);\n    promise.finally(() => cleanup()).then(resolve, reject);\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop;\n  });\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T,>(task: () => Promise<T>, cleanUp?: () => void): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve();\n    const value = await task();\n    return {\n      status: 'ok',\n      value\n    };\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error\n    };\n  } finally {\n    cleanUp?.();\n  }\n};\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T,>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(raceWithSignal(signal, promise).then(output => {\n      validateActive(signal);\n      return output;\n    }));\n  };\n};\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal);\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>(resolve => setTimeout(resolve, timeoutMs)));\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux';\nimport { isAction } from '../reduxImports';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport { createAction } from '../createAction';\nimport { nanoid } from '../nanoid';\nimport { TaskAbortError, listenerCancelled, listenerCompleted, taskCancelled, taskCompleted } from './exceptions';\nimport { createDelay, createPause, raceWithSignal, runTask, validateActive } from './task';\nimport type { AddListenerOverloads, AnyListenerPredicate, CreateListenerMiddlewareOptions, FallbackAddListenerOptions, ForkOptions, ForkedTask, ForkedTaskExecutor, ListenerEntry, ListenerErrorHandler, ListenerErrorInfo, ListenerMiddleware, ListenerMiddlewareInstance, TakePattern, TaskResult, TypedAddListener, TypedCreateListenerEntry, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\nimport { addAbortSignalListener, assertFunction, catchRejection, noop } from './utils';\nexport { TaskAbortError } from './exceptions';\nexport type { AsyncTaskExecutor, CreateListenerMiddlewareOptions, ForkedTask, ForkedTaskAPI, ForkedTaskExecutor, ListenerEffect, ListenerEffectAPI, ListenerErrorHandler, ListenerMiddleware, ListenerMiddlewareInstance, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, TypedAddListener, TypedRemoveListener, TypedStartListening, TypedStopListening, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\n\n//Overly-aggressive byte-shaving\nconst {\n  assign\n} = Object;\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const;\nconst alm = 'listenerMiddleware' as const;\nconst createFork = (parentAbortSignal: AbortSignal, parentBlockingPromises: Promise<any>[]) => {\n  const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));\n  return <T,>(taskExecutor: ForkedTaskExecutor<T>, opts?: ForkOptions): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor');\n    const childAbortController = new AbortController();\n    linkControllers(childAbortController);\n    const result = runTask<T>(async (): Promise<T> => {\n      validateActive(parentAbortSignal);\n      validateActive(childAbortController.signal);\n      const result = (await taskExecutor({\n        pause: createPause(childAbortController.signal),\n        delay: createDelay(childAbortController.signal),\n        signal: childAbortController.signal\n      })) as T;\n      validateActive(childAbortController.signal);\n      return result;\n    }, () => childAbortController.abort(taskCompleted));\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop));\n    }\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        childAbortController.abort(taskCancelled);\n      }\n    };\n  };\n};\nconst createTakePattern = <S,>(startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>, signal: AbortSignal): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>,>(predicate: P, timeout: number | undefined) => {\n    validateActive(signal);\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {};\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe();\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n        }\n      });\n      unsubscribe = () => {\n        stopListening();\n        reject();\n      };\n    });\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise];\n    if (timeout != null) {\n      promises.push(new Promise<null>(resolve => setTimeout(resolve, timeout, null)));\n    }\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises));\n      validateActive(signal);\n      return output;\n    } finally {\n      // Always clean up the listener\n      unsubscribe();\n    }\n  };\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) => catchRejection(take(predicate, timeout))) as TakePattern<S>;\n};\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let {\n    type,\n    actionCreator,\n    matcher,\n    predicate,\n    effect\n  } = options;\n  if (type) {\n    predicate = createAction(type).match;\n  } else if (actionCreator) {\n    type = actionCreator!.type;\n    predicate = actionCreator.match;\n  } else if (matcher) {\n    predicate = matcher;\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(21) : 'Creating or removing a listener requires one of the known fields for matching an action');\n  }\n  assertFunction(effect, 'options.listener');\n  return {\n    predicate,\n    type,\n    effect\n  };\n};\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> = /* @__PURE__ */assign((options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    predicate,\n    effect\n  } = getListenerEntryPropsFrom(options);\n  const entry: ListenerEntry<unknown> = {\n    id: nanoid(),\n    effect,\n    type,\n    predicate,\n    pending: new Set<AbortController>(),\n    unsubscribe: () => {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(22) : 'Unsubscribe not initialized');\n    }\n  };\n  return entry;\n}, {\n  withTypes: () => createListenerEntry\n}) as unknown as TypedCreateListenerEntry<unknown>;\nconst findListenerEntry = (listenerMap: Map<string, ListenerEntry>, options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    effect,\n    predicate\n  } = getListenerEntryPropsFrom(options);\n  return Array.from(listenerMap.values()).find(entry => {\n    const matchPredicateOrType = typeof type === 'string' ? entry.type === type : entry.predicate === predicate;\n    return matchPredicateOrType && entry.effect === effect;\n  });\n};\nconst cancelActiveListeners = (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>) => {\n  entry.pending.forEach(controller => {\n    controller.abort(listenerCancelled);\n  });\n};\nconst createClearListenerMiddleware = (listenerMap: Map<string, ListenerEntry>, executingListeners: Map<ListenerEntry, number>) => {\n  return () => {\n    for (const listener of executingListeners.keys()) {\n      cancelActiveListeners(listener);\n    }\n    listenerMap.clear();\n  };\n};\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (errorHandler: ListenerErrorHandler, errorToNotify: unknown, errorInfo: ListenerErrorInfo): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo);\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError;\n    }, 0);\n  }\n};\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/add`), {\n  withTypes: () => addListener\n}) as unknown as TypedAddListener<unknown>;\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */createAction(`${alm}/removeAll`);\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/remove`), {\n  withTypes: () => removeListener\n}) as unknown as TypedRemoveListener<unknown>;\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args);\n};\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {}) => {\n  const listenerMap = new Map<string, ListenerEntry>();\n\n  // Track listeners whose effect is currently executing so clearListeners can\n  // abort even listeners that have become unsubscribed while executing.\n  const executingListeners = new Map<ListenerEntry, number>();\n  const trackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 0;\n    executingListeners.set(entry, count + 1);\n  };\n  const untrackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 1;\n    if (count === 1) {\n      executingListeners.delete(entry);\n    } else {\n      executingListeners.set(entry, count - 1);\n    }\n  };\n  const {\n    extra,\n    onError = defaultErrorHandler\n  } = middlewareOptions;\n  assertFunction(onError, 'onError');\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id);\n    listenerMap.set(entry.id, entry);\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe();\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    };\n  };\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options as any);\n    return insertEntry(entry);\n  }) as AddListenerOverloads<any>;\n  assign(startListening, {\n    withTypes: () => startListening\n  });\n  const stopListening = (options: FallbackAddListenerOptions & UnsubscribeListenerOptions): boolean => {\n    const entry = findListenerEntry(listenerMap, options);\n    if (entry) {\n      entry.unsubscribe();\n      if (options.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    }\n    return !!entry;\n  };\n  assign(stopListening, {\n    withTypes: () => stopListening\n  });\n  const notifyListener = async (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>, action: unknown, api: MiddlewareAPI, getOriginalState: () => StateType) => {\n    const internalTaskController = new AbortController();\n    const take = createTakePattern(startListening as AddListenerOverloads<any>, internalTaskController.signal);\n    const autoJoinPromises: Promise<any>[] = [];\n    try {\n      entry.pending.add(internalTaskController);\n      trackExecutingListener(entry);\n      await Promise.resolve(entry.effect(action,\n      // Use assign() rather than ... to avoid extra helper functions added to bundle\n      assign({}, api, {\n        getOriginalState,\n        condition: (predicate: AnyListenerPredicate<any>, timeout?: number) => take(predicate, timeout).then(Boolean),\n        take,\n        delay: createDelay(internalTaskController.signal),\n        pause: createPause<any>(internalTaskController.signal),\n        extra,\n        signal: internalTaskController.signal,\n        fork: createFork(internalTaskController.signal, autoJoinPromises),\n        unsubscribe: entry.unsubscribe,\n        subscribe: () => {\n          listenerMap.set(entry.id, entry);\n        },\n        cancelActiveListeners: () => {\n          entry.pending.forEach((controller, _, set) => {\n            if (controller !== internalTaskController) {\n              controller.abort(listenerCancelled);\n              set.delete(controller);\n            }\n          });\n        },\n        cancel: () => {\n          internalTaskController.abort(listenerCancelled);\n          entry.pending.delete(internalTaskController);\n        },\n        throwIfCancelled: () => {\n          validateActive(internalTaskController.signal);\n        }\n      })));\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect'\n        });\n      }\n    } finally {\n      await Promise.all(autoJoinPromises);\n      internalTaskController.abort(listenerCompleted); // Notify that the task has completed\n      untrackExecutingListener(entry);\n      entry.pending.delete(internalTaskController);\n    }\n  };\n  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);\n  const middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument> = api => next => action => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action);\n    }\n    if (addListener.match(action)) {\n      return startListening(action.payload as any);\n    }\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware();\n      return;\n    }\n    if (removeListener.match(action)) {\n      return stopListening(action.payload);\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState();\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);\n      }\n      return originalState as StateType;\n    };\n    let result: unknown;\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action);\n      if (listenerMap.size > 0) {\n        const currentState = api.getState();\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values());\n        for (const entry of listenerEntries) {\n          let runListener = false;\n          try {\n            runListener = entry.predicate(action, currentState, originalState);\n          } catch (predicateError) {\n            runListener = false;\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate'\n            });\n          }\n          if (!runListener) {\n            continue;\n          }\n          notifyListener(entry, action, api, getOriginalState);\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN;\n    }\n    return result;\n  };\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;\n};","import type { Dispatch, Middleware, UnknownAction } from 'redux';\nimport { compose } from '../reduxImports';\nimport { createAction } from '../createAction';\nimport { isAllOf } from '../matchers';\nimport { nanoid } from '../nanoid';\nimport { getOrInsertComputed } from '../utils';\nimport type { AddMiddleware, DynamicMiddleware, DynamicMiddlewareInstance, MiddlewareEntry, WithMiddleware } from './types';\nexport type { DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './types';\nconst createMiddlewareEntry = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(middleware: Middleware<any, State, DispatchType>): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map()\n});\nconst matchInstance = (instanceId: string) => (action: any): action is {\n  meta: {\n    instanceId: string;\n  };\n} => action?.meta?.instanceId === instanceId;\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid();\n  const middlewareMap = new Map<Middleware<any, State, DispatchType>, MiddlewareEntry<State, DispatchType>>();\n  const withMiddleware = Object.assign(createAction('dynamicMiddleware/add', (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n    payload: middlewares,\n    meta: {\n      instanceId\n    }\n  })), {\n    withTypes: () => withMiddleware\n  }) as WithMiddleware<State, DispatchType>;\n  const addMiddleware = Object.assign(function addMiddleware(...middlewares: Middleware<any, State, DispatchType>[]) {\n    middlewares.forEach(middleware => {\n      getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);\n    });\n  }, {\n    withTypes: () => addMiddleware\n  }) as AddMiddleware<State, DispatchType>;\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = api => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map(entry => getOrInsertComputed(entry.applied, api, entry.middleware));\n    return compose(...appliedMiddleware);\n  };\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n  const middleware: DynamicMiddleware<State, DispatchType> = api => next => action => {\n    if (isWithMiddleware(action)) {\n      addMiddleware(...action.payload);\n      return api.dispatch;\n    }\n    return getFinalMiddleware(api)(next)(action);\n  };\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { PreloadedStateShapeFromReducersMapObject, Reducer, StateFromReducersMapObject, UnknownAction } from 'redux';\nimport { combineReducers } from 'redux';\nimport { nanoid } from './nanoid';\nimport type { Id, NonUndefined, Tail, UnionToIntersection, WithOptionalProp } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\ntype SliceLike<ReducerPath extends string, State, PreloadedState = State> = {\n  reducerPath: ReducerPath;\n  reducer: Reducer<State, any, PreloadedState>;\n};\ntype AnySliceLike = SliceLike<string, any>;\ntype SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;\ntype SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;\ntype SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;\nexport type WithSlice<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikeState<A> };\nexport type WithSlicePreloadedState<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A> };\ntype ReducerMap = Record<string, Reducer>;\ntype ExistingSliceLike<DeclaredState, PreloadedState> = { [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>> }[keyof DeclaredState];\nexport type InjectConfig = {\n  /**\n   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.\n   */\n  overrideExisting?: boolean;\n};\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;\n  };\n}\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;\ntype InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;\nconst isSliceLike = (maybeSliceLike: AnySliceLike | ReducerMap): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string';\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) => slices.flatMap<[string, Reducer]>(sliceOrMap => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original');\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE];\nconst stateProxyMap = new WeakMap<object, object>();\nconst createStateProxy = <State extends object,>(state: State, reducerMap: Partial<Record<PropertyKey, Reducer>>, initialStateCache: Record<PropertyKey, unknown>) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {\n  get: (target, prop, receiver) => {\n    if (prop === ORIGINAL_STATE) return target;\n    const result = Reflect.get(target, prop, receiver);\n    if (typeof result === 'undefined') {\n      const cached = initialStateCache[prop];\n      if (typeof cached !== 'undefined') return cached;\n      const reducer = reducerMap[prop];\n      if (reducer) {\n        // ensure action type is random, to prevent reducer treating it differently\n        const reducerResult = reducer(undefined, {\n          type: nanoid()\n        });\n        if (typeof reducerResult === 'undefined') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). ` + `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + `you can use null instead of undefined.`);\n        }\n        initialStateCache[prop] = reducerResult;\n        return reducerResult;\n      }\n    }\n    return result;\n  }\n})) as State;\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(25) : 'original must be used on state Proxy');\n  }\n  return state[ORIGINAL_STATE];\n};\nconst emptyObject = {};\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state;\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>> {\n  const reducerMap = Object.fromEntries(getReducers(slices));\n  const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;\n  let reducer = getReducer();\n  function combinedReducer(state: Record<string, unknown>, action: UnknownAction) {\n    return reducer(state, action);\n  }\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n  const initialStateCache: Record<PropertyKey, unknown> = {};\n  const inject = (slice: AnySliceLike, config: InjectConfig = {}): typeof combinedReducer => {\n    const {\n      reducerPath,\n      reducer: reducerToInject\n    } = slice;\n    const currentReducer = reducerMap[reducerPath];\n    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n      }\n      return combinedReducer;\n    }\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath];\n    }\n    reducerMap[reducerPath] = reducerToInject;\n    reducer = getReducer();\n    return combinedReducer;\n  };\n  const selector = Object.assign(function makeSelector<State extends object, RootState, Args extends any[]>(selectorFn: (state: State, ...args: Args) => any, selectState?: (rootState: RootState, ...args: Args) => State) {\n    return function selector(state: State, ...args: Args) {\n      return selectorFn(createStateProxy(selectState ? selectState(state as any, ...args) : state, reducerMap, initialStateCache), ...args);\n    };\n  }, {\n    original\n  });\n  return Object.assign(combinedReducer, {\n    inject,\n    selector\n  }) as any;\n}","/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` + 'use the non-minified dev environment for full errors. ';\n}"],"mappings":"AAGA,WAAc,QACd,OAAS,UAAAA,GAAQ,YAAAC,OAAgB,QCJjC,OAAS,WAAAC,EAAS,WAAAC,EAAoB,WAAXC,EAA4B,eAAAC,EAAa,yBAAAC,OAA6B,QDOjG,OAAS,kBAAAC,GAAgB,cAAAC,OAAkB,WEP3C,OAAS,yBAAAC,GAAuB,kBAAAC,OAAsB,WCE/C,IAAMC,GAA+D,IAAIC,IAAoB,CAClG,IAAMC,EAAkBC,GAA8B,GAAGF,CAAI,EACvDG,EAA0B,OAAO,OAAO,IAAIH,IAAoB,CACpE,IAAMI,EAAWH,EAAe,GAAGD,CAAI,EACjCK,EAAkB,CAACC,KAAmBC,IAAoBH,EAASI,EAAQF,CAAK,EAAIG,EAAQH,CAAK,EAAIA,EAAO,GAAGC,CAAI,EACzH,cAAO,OAAOF,EAAiBD,CAAQ,EAChCC,CACT,EAAG,CACD,UAAW,IAAMF,CACnB,CAAC,EACD,OAAOA,CACT,EASaA,GACbJ,GAA+BW,EAAc,ECvB7C,OAAS,eAAAC,GAAa,mBAAAC,GAAiB,mBAAAC,GAAiB,WAAAC,EAAS,iBAAAC,EAAe,YAAAC,MAAgB,QCmNzF,IAAMC,GAA2C,OAAO,OAAW,KAAgB,OAAe,qCAAwC,OAAe,qCAAuC,UAAY,CACjN,GAAI,UAAU,SAAW,EACzB,OAAI,OAAO,UAAU,CAAC,GAAM,SAAiBC,EACtCA,EAAQ,MAAM,KAAM,SAA8B,CAC3D,EAKaC,GAET,OAAO,OAAW,KAAgB,OAAe,6BAAgC,OAAe,6BAA+B,UAAY,CAC7I,OAAO,SAAUC,EAA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AACD,EAAO,kBAAoBG,GAAkBA,IAAmBD,IAMjEF,EAAO,kBAAoBG,IAAmBD,GAChD,OAAOvB,EAAkBsB,CAAW,EAEtCvB,EAAWuB,CAAW,EAAIC,EAC1BhB,EAAUQ,EAAW,GACdE,CACT,EACMQ,EAAW,OAAO,OAAO,SAA2EC,EAAkDC,EAA8D,CACxN,OAAO,SAAkB7B,KAAiB8B,EAAY,CACpD,OAAOF,EAAW7B,GAAiB8B,EAAcA,EAAY7B,EAAc,GAAG8B,CAAI,EAAI9B,EAAOC,EAAYC,CAAiB,EAAG,GAAG4B,CAAI,CACtI,CACF,EAAG,CACD,SAAAjB,EACF,CAAC,EACD,OAAO,OAAO,OAAOM,EAAiB,CACpC,OAAAE,EACA,SAAAM,CACF,CAAC,CACH,CC9SO,SAASI,EAAuBC,EAAc,CACnD,MAAO,iCAAiCA,CAAI,oDAAoDA,CAAI,iFACtG","names":["freeze","original","current","isDraft","produce","isDraftable","setUseStrictIteration","createSelector","lruMemoize","createSelectorCreator","weakMapMemoize","createDraftSafeSelectorCreator","args","createSelector","createSelectorCreator","createDraftSafeSelector","selector","wrappedSelector","value","rest","isDraft","current","weakMapMemoize","createStore","combineReducers","applyMiddleware","compose","isPlainObject","isAction","composeWithDevTools","compose","devToolsEnhancer","noop","thunkMiddleware","withExtraArgument","hasMatchFunction","v","createAction","type","prepareAction","actionCreator","args","prepared","formatProdErrorMessage","action","isAction","isActionCreator","hasMatchFunction","isFSA","isValidKey","key","getMessage","type","splitType","actionName","createActionCreatorInvariantMiddleware","options","next","action","Tuple","_Tuple","items","arr","freezeDraftable","val","isDraftable","produce","getOrInsertComputed","map","key","compute","isImmutableDefault","value","createImmutableStateInvariantMiddleware","options","next","action","stringify","getSerialize","isPlain","val","type","isPlainObject","findNonSerializableValue","value","path","isSerializable","getEntries","ignoredPaths","cache","foundNestedSerializable","entries","hasIgnoredPaths","key","nestedValue","nestedPath","ignored","isNestedFrozen","createSerializableStateInvariantMiddleware","options","next","action","isBoolean","x","buildGetDefaultMiddleware","options","thunk","immutableCheck","serializableCheck","actionCreatorCheck","middlewareArray","Tuple","thunkMiddleware","withExtraArgument","SHOULD_AUTOBATCH","prepareAutoBatched","payload","createQueueWithTimer","timeout","notify","autoBatchEnhancer","options","next","args","store","notifying","shouldNotifyAtEndOfTick","notificationQueued","listeners","queueCallback","notifyListeners","l","listener","wrappedListener","unsubscribe","action","buildGetDefaultEnhancers","middlewareEnhancer","options","autoBatch","enhancerArray","Tuple","autoBatchEnhancer","configureStore","options","getDefaultMiddleware","buildGetDefaultMiddleware","reducer","middleware","devTools","duplicateMiddlewareCheck","preloadedState","enhancers","rootReducer","isPlainObject","combineReducers","formatProdErrorMessage","finalMiddleware","finalCompose","compose","composeWithDevTools","middlewareEnhancer","applyMiddleware","getDefaultEnhancers","buildGetDefaultEnhancers","storeEnhancers","composedEnhancer","createStore","executeReducerBuilderCallback","builderCallback","actionsMap","actionMatchers","defaultCaseReducer","builder","typeOrActionCreator","reducer","type","formatProdErrorMessage","asyncThunk","reducers","matcher","isStateFunction","x","createReducer","initialState","mapOrBuilderCallback","actionsMap","finalActionMatchers","finalDefaultCaseReducer","executeReducerBuilderCallback","getInitialState","freezeDraftable","frozenInitialState","reducer","state","action","caseReducers","matcher","cr","previousState","caseReducer","isDraft","result","isDraftable","produce","draft","matches","matcher","action","hasMatchFunction","isAnyOf","matchers","isAllOf","hasExpectedRequestMetadata","validStatus","hasValidRequestId","hasValidRequestStatus","isAsyncThunkArray","a","isPending","asyncThunks","asyncThunk","isRejected","isRejectedWithValue","hasFlag","isFulfilled","isAsyncThunkAction","urlAlphabet","nanoid","size","id","i","commonProperties","RejectWithValue","payload","meta","FulfillWithMeta","miniSerializeError","value","simpleError","property","externalAbortMessage","createAsyncThunk","typePrefix","payloadCreator","options","fulfilled","createAction","requestId","arg","pending","rejected","error","actionCreator","signal","dispatch","getState","extra","nanoid","abortController","abortHandler","abortReason","abort","reason","promise","finalAction","conditionResult","isThenable","abortedPromise","_","reject","result","err","unwrapResult","isAnyOf","action","asyncThunkSymbol","asyncThunkCreator","createAsyncThunk","ReducerType","getType","slice","actionKey","buildCreateSlice","creators","cAT","options","name","reducerPath","formatProdErrorMessage","reducers","buildReducerCreators","reducerNames","context","contextMethods","typeOrActionCreator","reducer","type","matcher","actionCreator","reducerName","reducerDefinition","reducerDetails","isAsyncThunkSliceReducerDefinition","handleThunkCaseReducerDefinition","handleNormalReducerDefinition","buildReducer","extraReducers","actionMatchers","defaultCaseReducer","executeReducerBuilderCallback","finalCaseReducers","createReducer","builder","key","sM","m","selectSelf","state","injectedSelectorCache","injectedStateCache","_reducer","action","getInitialState","makeSelectorProps","injected","selectSlice","sliceState","getOrInsertComputed","getSelectors","selectState","selectorCache","map","selector","wrapSelector","injectable","pathOpt","config","newReducerPath","wrapper","rootState","args","createSlice","asyncThunk","payloadCreator","caseReducer","prepare","createNotation","maybeReducerWithPrepare","prepareCallback","isCaseReducerWithPrepareDefinition","createAction","fulfilled","pending","rejected","settled","thunk","noop","getInitialEntityState","createInitialStateFactory","stateAdapter","getInitialState","additionalState","entities","state","createSelectorsFactory","getSelectors","selectState","options","createSelector","createDraftSafeSelector","selectIds","state","selectEntities","selectAll","ids","entities","id","selectId","_","selectById","selectTotal","selectGlobalizedEntities","isDraftTyped","isDraft","createSingleArgumentStateOperator","mutator","operator","createStateOperator","_","state","arg","isPayloadActionArgument","isFSA","runMutator","draft","produce","selectIdValue","entity","selectId","ensureEntitiesArray","entities","getCurrent","value","isDraft","current","splitAddedUpdatedEntities","newEntities","state","existingIdsArray","existingIds","added","addedIds","updated","id","createUnsortedStateAdapter","selectId","addOneMutably","entity","state","key","selectIdValue","addManyMutably","newEntities","ensureEntitiesArray","setOneMutably","setManyMutably","setAllMutably","removeOneMutably","removeManyMutably","keys","didMutate","id","removeAllMutably","takeNewKey","update","original","updated","newKey","hasNewKey","updateOneMutably","updateManyMutably","updates","newKeys","updatesPerEntity","e","upsertOneMutably","upsertManyMutably","added","splitAddedUpdatedEntities","createSingleArgumentStateOperator","createStateOperator","findInsertIndex","sortedItems","item","comparisonFunction","lowIndex","highIndex","middleIndex","currentItem","insert","insertAtIndex","createSortedStateAdapter","selectId","comparer","removeOne","removeMany","removeAll","createUnsortedStateAdapter","addOneMutably","entity","state","addManyMutably","newEntities","existingIds","ensureEntitiesArray","existingKeys","getCurrent","addedKeys","models","model","modelId","selectIdValue","notAdded","mergeFunction","setOneMutably","setManyMutably","deduplicatedEntities","entityId","setAllMutably","updateOneMutably","update","updateManyMutably","updates","appliedUpdates","replacedIds","newId","oldIndex","upsertOneMutably","upsertManyMutably","added","updated","existingIdsArray","splitAddedUpdatedEntities","areArraysEqual","a","b","i","addedItems","currentEntities","currentIds","stateEntities","ids","sortedEntities","id","wasPreviouslyEmpty","newSortedIds","createStateOperator","createEntityAdapter","options","selectId","sortComparer","instance","stateAdapter","createSortedStateAdapter","createUnsortedStateAdapter","stateFactory","createInitialStateFactory","selectorsFactory","createSelectorsFactory","task","listener","completed","cancelled","taskCancelled","taskCompleted","listenerCancelled","listenerCompleted","TaskAbortError","code","assertFunction","func","expected","formatProdErrorMessage","noop","catchRejection","promise","onError","addAbortSignalListener","abortSignal","callback","validateActive","signal","TaskAbortError","raceWithSignal","promise","cleanup","noop","resolve","reject","notifyRejection","addAbortSignalListener","runTask","task","cleanUp","error","createPause","catchRejection","output","createDelay","pause","timeoutMs","assign","INTERNAL_NIL_TOKEN","alm","createFork","parentAbortSignal","parentBlockingPromises","linkControllers","controller","addAbortSignalListener","taskExecutor","opts","assertFunction","childAbortController","result","runTask","validateActive","createPause","createDelay","taskCompleted","noop","taskCancelled","createTakePattern","startListening","signal","take","predicate","timeout","unsubscribe","promises","resolve","reject","stopListening","action","listenerApi","output","raceWithSignal","catchRejection","getListenerEntryPropsFrom","options","type","actionCreator","matcher","effect","createAction","formatProdErrorMessage","createListenerEntry","nanoid","findListenerEntry","listenerMap","entry","cancelActiveListeners","listenerCancelled","createClearListenerMiddleware","executingListeners","listener","safelyNotifyError","errorHandler","errorToNotify","errorInfo","errorHandlerError","addListener","clearAllListeners","removeListener","defaultErrorHandler","args","createListenerMiddleware","middlewareOptions","trackExecutingListener","count","untrackExecutingListener","extra","onError","insertEntry","cancelOptions","notifyListener","api","getOriginalState","internalTaskController","autoJoinPromises","_","set","listenerError","TaskAbortError","listenerCompleted","clearListenerMiddleware","next","isAction","originalState","currentState","listenerEntries","runListener","predicateError","createMiddlewareEntry","middleware","matchInstance","instanceId","action","createDynamicMiddleware","nanoid","middlewareMap","withMiddleware","createAction","middlewares","addMiddleware","getOrInsertComputed","getFinalMiddleware","api","appliedMiddleware","entry","compose","isWithMiddleware","isAllOf","next","combineReducers","isSliceLike","maybeSliceLike","getReducers","slices","sliceOrMap","ORIGINAL_STATE","isStateProxy","value","stateProxyMap","createStateProxy","state","reducerMap","initialStateCache","getOrInsertComputed","target","prop","receiver","result","cached","reducer","reducerResult","nanoid","formatProdErrorMessage","original","emptyObject","noopReducer","combineSlices","getReducer","combineReducers","combinedReducer","action","inject","slice","config","reducerPath","reducerToInject","currentReducer","selector","selectorFn","selectState","args","formatProdErrorMessage","code"]}
Index: node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js
===================================================================
--- node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2337 @@
+var __defProp = Object.defineProperty;
+var __defProps = Object.defineProperties;
+var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
+var __getOwnPropSymbols = Object.getOwnPropertySymbols;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __propIsEnum = Object.prototype.propertyIsEnumerable;
+var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __spreadValues = (a, b) => {
+  for (var prop in b || (b = {}))
+    if (__hasOwnProp.call(b, prop))
+      __defNormalProp(a, prop, b[prop]);
+  if (__getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(b)) {
+      if (__propIsEnum.call(b, prop))
+        __defNormalProp(a, prop, b[prop]);
+    }
+  return a;
+};
+var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
+var __objRest = (source, exclude) => {
+  var target = {};
+  for (var prop in source)
+    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
+      target[prop] = source[prop];
+  if (source != null && __getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(source)) {
+      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
+        target[prop] = source[prop];
+    }
+  return target;
+};
+var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
+
+// src/index.ts
+export * from "redux";
+import { freeze, original as original2 } from "immer";
+
+// src/immerImports.ts
+import { current, isDraft, produce, isDraftable, setUseStrictIteration } from "immer";
+
+// src/index.ts
+import { createSelector, lruMemoize } from "reselect";
+
+// src/reselectImports.ts
+import { createSelectorCreator, weakMapMemoize } from "reselect";
+
+// src/createDraftSafeSelector.ts
+var createDraftSafeSelectorCreator = (...args) => {
+  const createSelector2 = createSelectorCreator(...args);
+  const createDraftSafeSelector2 = Object.assign((...args2) => {
+    const selector = createSelector2(...args2);
+    const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
+    Object.assign(wrappedSelector, selector);
+    return wrappedSelector;
+  }, {
+    withTypes: () => createDraftSafeSelector2
+  });
+  return createDraftSafeSelector2;
+};
+var createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(weakMapMemoize);
+
+// src/reduxImports.ts
+import { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from "redux";
+
+// src/devtoolsExtension.ts
+var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
+  if (arguments.length === 0) return void 0;
+  if (typeof arguments[0] === "object") return compose;
+  return compose.apply(null, arguments);
+};
+var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
+  return function(noop3) {
+    return noop3;
+  };
+};
+
+// src/getDefaultMiddleware.ts
+import { thunk as thunkMiddleware, withExtraArgument } from "redux-thunk";
+
+// src/tsHelpers.ts
+var hasMatchFunction = (v) => {
+  return v && typeof v.match === "function";
+};
+
+// src/createAction.ts
+function createAction(type, prepareAction) {
+  function actionCreator(...args) {
+    if (prepareAction) {
+      let prepared = prepareAction(...args);
+      if (!prepared) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
+      }
+      return __spreadValues(__spreadValues({
+        type,
+        payload: prepared.payload
+      }, "meta" in prepared && {
+        meta: prepared.meta
+      }), "error" in prepared && {
+        error: prepared.error
+      });
+    }
+    return {
+      type,
+      payload: args[0]
+    };
+  }
+  actionCreator.toString = () => `${type}`;
+  actionCreator.type = type;
+  actionCreator.match = (action) => isAction(action) && action.type === type;
+  return actionCreator;
+}
+function isActionCreator(action) {
+  return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
+  hasMatchFunction(action);
+}
+function isFSA(action) {
+  return isAction(action) && Object.keys(action).every(isValidKey);
+}
+function isValidKey(key) {
+  return ["type", "payload", "error", "meta"].indexOf(key) > -1;
+}
+
+// src/actionCreatorInvariantMiddleware.ts
+function getMessage(type) {
+  const splitType = type ? `${type}`.split("/") : [];
+  const actionName = splitType[splitType.length - 1] || "actionCreator";
+  return `Detected an action creator with type "${type || "unknown"}" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`;
+}
+function createActionCreatorInvariantMiddleware(options = {}) {
+  if (process.env.NODE_ENV === "production") {
+    return () => (next) => (action) => next(action);
+  }
+  const {
+    isActionCreator: isActionCreator2 = isActionCreator
+  } = options;
+  return () => (next) => (action) => {
+    if (isActionCreator2(action)) {
+      console.warn(getMessage(action.type));
+    }
+    return next(action);
+  };
+}
+
+// src/utils.ts
+function getTimeMeasureUtils(maxDelay, fnName) {
+  let elapsed = 0;
+  return {
+    measureTime(fn) {
+      const started = Date.now();
+      try {
+        return fn();
+      } finally {
+        const finished = Date.now();
+        elapsed += finished - started;
+      }
+    },
+    warnIfExceeded() {
+      if (elapsed > maxDelay) {
+        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. 
+If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
+It is disabled in production builds, so you don't need to worry about that.`);
+      }
+    }
+  };
+}
+var Tuple = class _Tuple extends Array {
+  constructor(...items) {
+    super(...items);
+    Object.setPrototypeOf(this, _Tuple.prototype);
+  }
+  static get [Symbol.species]() {
+    return _Tuple;
+  }
+  concat(...arr) {
+    return super.concat.apply(this, arr);
+  }
+  prepend(...arr) {
+    if (arr.length === 1 && Array.isArray(arr[0])) {
+      return new _Tuple(...arr[0].concat(this));
+    }
+    return new _Tuple(...arr.concat(this));
+  }
+};
+function freezeDraftable(val) {
+  return isDraftable(val) ? produce(val, () => {
+  }) : val;
+}
+function getOrInsertComputed(map, key, compute) {
+  if (map.has(key)) return map.get(key);
+  return map.set(key, compute(key)).get(key);
+}
+
+// src/immutableStateInvariantMiddleware.ts
+function isImmutableDefault(value) {
+  return typeof value !== "object" || value == null || Object.isFrozen(value);
+}
+function trackForMutations(isImmutable, ignoredPaths, obj) {
+  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);
+  return {
+    detectMutations() {
+      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);
+    }
+  };
+}
+function trackProperties(isImmutable, ignoredPaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
+  const tracked = {
+    value: obj
+  };
+  if (!isImmutable(obj) && !checkedObjects.has(obj)) {
+    checkedObjects.add(obj);
+    tracked.children = {};
+    const hasIgnoredPaths = ignoredPaths.length > 0;
+    for (const key in obj) {
+      const nestedPath = path ? path + "." + key : key;
+      if (hasIgnoredPaths) {
+        const hasMatches = ignoredPaths.some((ignored) => {
+          if (ignored instanceof RegExp) {
+            return ignored.test(nestedPath);
+          }
+          return nestedPath === ignored;
+        });
+        if (hasMatches) {
+          continue;
+        }
+      }
+      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);
+    }
+  }
+  return tracked;
+}
+function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
+  const prevObj = trackedProperty ? trackedProperty.value : void 0;
+  const sameRef = prevObj === obj;
+  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
+    return {
+      wasMutated: true,
+      path
+    };
+  }
+  if (isImmutable(prevObj) || isImmutable(obj)) {
+    return {
+      wasMutated: false
+    };
+  }
+  const keysToDetect = {};
+  for (let key in trackedProperty.children) {
+    keysToDetect[key] = true;
+  }
+  for (let key in obj) {
+    keysToDetect[key] = true;
+  }
+  const hasIgnoredPaths = ignoredPaths.length > 0;
+  for (let key in keysToDetect) {
+    const nestedPath = path ? path + "." + key : key;
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath);
+        }
+        return nestedPath === ignored;
+      });
+      if (hasMatches) {
+        continue;
+      }
+    }
+    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
+    if (result.wasMutated) {
+      return result;
+    }
+  }
+  return {
+    wasMutated: false
+  };
+}
+function createImmutableStateInvariantMiddleware(options = {}) {
+  if (process.env.NODE_ENV === "production") {
+    return () => (next) => (action) => next(action);
+  } else {
+    let stringify2 = function(obj, serializer, indent, decycler) {
+      return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
+    }, getSerialize2 = function(serializer, decycler) {
+      let stack = [], keys = [];
+      if (!decycler) decycler = function(_, value) {
+        if (stack[0] === value) return "[Circular ~]";
+        return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
+      };
+      return function(key, value) {
+        if (stack.length > 0) {
+          var thisPos = stack.indexOf(this);
+          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
+          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
+          if (~stack.indexOf(value)) value = decycler.call(this, key, value);
+        } else stack.push(value);
+        return serializer == null ? value : serializer.call(this, key, value);
+      };
+    };
+    var stringify = stringify2, getSerialize = getSerialize2;
+    let {
+      isImmutable = isImmutableDefault,
+      ignoredPaths,
+      warnAfter = 32
+    } = options;
+    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
+    return ({
+      getState
+    }) => {
+      let state = getState();
+      let tracker = track(state);
+      let result;
+      return (next) => (action) => {
+        const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
+        measureUtils.measureTime(() => {
+          state = getState();
+          result = tracker.detectMutations();
+          tracker = track(state);
+          if (result.wasMutated) {
+            throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
+          }
+        });
+        const dispatchedAction = next(action);
+        measureUtils.measureTime(() => {
+          state = getState();
+          result = tracker.detectMutations();
+          tracker = track(state);
+          if (result.wasMutated) {
+            throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
+          }
+        });
+        measureUtils.warnIfExceeded();
+        return dispatchedAction;
+      };
+    };
+  }
+}
+
+// src/serializableStateInvariantMiddleware.ts
+function isPlain(val) {
+  const type = typeof val;
+  return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
+}
+function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
+  let foundNestedSerializable;
+  if (!isSerializable(value)) {
+    return {
+      keyPath: path || "<root>",
+      value
+    };
+  }
+  if (typeof value !== "object" || value === null) {
+    return false;
+  }
+  if (cache == null ? void 0 : cache.has(value)) return false;
+  const entries = getEntries != null ? getEntries(value) : Object.entries(value);
+  const hasIgnoredPaths = ignoredPaths.length > 0;
+  for (const [key, nestedValue] of entries) {
+    const nestedPath = path ? path + "." + key : key;
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath);
+        }
+        return nestedPath === ignored;
+      });
+      if (hasMatches) {
+        continue;
+      }
+    }
+    if (!isSerializable(nestedValue)) {
+      return {
+        keyPath: nestedPath,
+        value: nestedValue
+      };
+    }
+    if (typeof nestedValue === "object") {
+      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
+      if (foundNestedSerializable) {
+        return foundNestedSerializable;
+      }
+    }
+  }
+  if (cache && isNestedFrozen(value)) cache.add(value);
+  return false;
+}
+function isNestedFrozen(value) {
+  if (!Object.isFrozen(value)) return false;
+  for (const nestedValue of Object.values(value)) {
+    if (typeof nestedValue !== "object" || nestedValue === null) continue;
+    if (!isNestedFrozen(nestedValue)) return false;
+  }
+  return true;
+}
+function createSerializableStateInvariantMiddleware(options = {}) {
+  if (process.env.NODE_ENV === "production") {
+    return () => (next) => (action) => next(action);
+  } else {
+    const {
+      isSerializable = isPlain,
+      getEntries,
+      ignoredActions = [],
+      ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
+      ignoredPaths = [],
+      warnAfter = 32,
+      ignoreState = false,
+      ignoreActions = false,
+      disableCache = false
+    } = options;
+    const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
+    return (storeAPI) => (next) => (action) => {
+      if (!isAction(action)) {
+        return next(action);
+      }
+      const result = next(action);
+      const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
+      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
+        measureUtils.measureTime(() => {
+          const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
+          if (foundActionNonSerializableValue) {
+            const {
+              keyPath,
+              value
+            } = foundActionNonSerializableValue;
+            console.error(`A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`, value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
+          }
+        });
+      }
+      if (!ignoreState) {
+        measureUtils.measureTime(() => {
+          const state = storeAPI.getState();
+          const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
+          if (foundStateNonSerializableValue) {
+            const {
+              keyPath,
+              value
+            } = foundStateNonSerializableValue;
+            console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
+Take a look at the reducer(s) handling this action type: ${action.type}.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
+          }
+        });
+        measureUtils.warnIfExceeded();
+      }
+      return result;
+    };
+  }
+}
+
+// src/getDefaultMiddleware.ts
+function isBoolean(x) {
+  return typeof x === "boolean";
+}
+var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
+  const {
+    thunk = true,
+    immutableCheck = true,
+    serializableCheck = true,
+    actionCreatorCheck = true
+  } = options != null ? options : {};
+  let middlewareArray = new Tuple();
+  if (thunk) {
+    if (isBoolean(thunk)) {
+      middlewareArray.push(thunkMiddleware);
+    } else {
+      middlewareArray.push(withExtraArgument(thunk.extraArgument));
+    }
+  }
+  if (process.env.NODE_ENV !== "production") {
+    if (immutableCheck) {
+      let immutableOptions = {};
+      if (!isBoolean(immutableCheck)) {
+        immutableOptions = immutableCheck;
+      }
+      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
+    }
+    if (serializableCheck) {
+      let serializableOptions = {};
+      if (!isBoolean(serializableCheck)) {
+        serializableOptions = serializableCheck;
+      }
+      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
+    }
+    if (actionCreatorCheck) {
+      let actionCreatorOptions = {};
+      if (!isBoolean(actionCreatorCheck)) {
+        actionCreatorOptions = actionCreatorCheck;
+      }
+      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
+    }
+  }
+  return middlewareArray;
+};
+
+// src/autoBatchEnhancer.ts
+var SHOULD_AUTOBATCH = "RTK_autoBatch";
+var prepareAutoBatched = () => (payload) => ({
+  payload,
+  meta: {
+    [SHOULD_AUTOBATCH]: true
+  }
+});
+var createQueueWithTimer = (timeout) => {
+  return (notify) => {
+    setTimeout(notify, timeout);
+  };
+};
+var autoBatchEnhancer = (options = {
+  type: "raf"
+}) => (next) => (...args) => {
+  const store = next(...args);
+  let notifying = true;
+  let shouldNotifyAtEndOfTick = false;
+  let notificationQueued = false;
+  const listeners = /* @__PURE__ */ new Set();
+  const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? (
+    // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
+    typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10)
+  ) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
+  const notifyListeners = () => {
+    notificationQueued = false;
+    if (shouldNotifyAtEndOfTick) {
+      shouldNotifyAtEndOfTick = false;
+      listeners.forEach((l) => l());
+    }
+  };
+  return Object.assign({}, store, {
+    // Override the base `store.subscribe` method to keep original listeners
+    // from running if we're delaying notifications
+    subscribe(listener2) {
+      const wrappedListener = () => notifying && listener2();
+      const unsubscribe = store.subscribe(wrappedListener);
+      listeners.add(listener2);
+      return () => {
+        unsubscribe();
+        listeners.delete(listener2);
+      };
+    },
+    // Override the base `store.dispatch` method so that we can check actions
+    // for the `shouldAutoBatch` flag and determine if batching is active
+    dispatch(action) {
+      var _a;
+      try {
+        notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);
+        shouldNotifyAtEndOfTick = !notifying;
+        if (shouldNotifyAtEndOfTick) {
+          if (!notificationQueued) {
+            notificationQueued = true;
+            queueCallback(notifyListeners);
+          }
+        }
+        return store.dispatch(action);
+      } finally {
+        notifying = true;
+      }
+    }
+  });
+};
+
+// src/getDefaultEnhancers.ts
+var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
+  const {
+    autoBatch = true
+  } = options != null ? options : {};
+  let enhancerArray = new Tuple(middlewareEnhancer);
+  if (autoBatch) {
+    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
+  }
+  return enhancerArray;
+};
+
+// src/configureStore.ts
+function configureStore(options) {
+  const getDefaultMiddleware = buildGetDefaultMiddleware();
+  const {
+    reducer = void 0,
+    middleware,
+    devTools = true,
+    duplicateMiddlewareCheck = true,
+    preloadedState = void 0,
+    enhancers = void 0
+  } = options || {};
+  let rootReducer;
+  if (typeof reducer === "function") {
+    rootReducer = reducer;
+  } else if (isPlainObject(reducer)) {
+    rootReducer = combineReducers(reducer);
+  } else {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
+  }
+  if (process.env.NODE_ENV !== "production" && middleware && typeof middleware !== "function") {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
+  }
+  let finalMiddleware;
+  if (typeof middleware === "function") {
+    finalMiddleware = middleware(getDefaultMiddleware);
+    if (process.env.NODE_ENV !== "production" && !Array.isArray(finalMiddleware)) {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
+    }
+  } else {
+    finalMiddleware = getDefaultMiddleware();
+  }
+  if (process.env.NODE_ENV !== "production" && finalMiddleware.some((item) => typeof item !== "function")) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
+  }
+  if (process.env.NODE_ENV !== "production" && duplicateMiddlewareCheck) {
+    let middlewareReferences = /* @__PURE__ */ new Set();
+    finalMiddleware.forEach((middleware2) => {
+      if (middlewareReferences.has(middleware2)) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(42) : "Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");
+      }
+      middlewareReferences.add(middleware2);
+    });
+  }
+  let finalCompose = compose;
+  if (devTools) {
+    finalCompose = composeWithDevTools(__spreadValues({
+      // Enable capture of stack traces for dispatched Redux actions
+      trace: process.env.NODE_ENV !== "production"
+    }, typeof devTools === "object" && devTools));
+  }
+  const middlewareEnhancer = applyMiddleware(...finalMiddleware);
+  const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
+  if (process.env.NODE_ENV !== "production" && enhancers && typeof enhancers !== "function") {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
+  }
+  let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
+  if (process.env.NODE_ENV !== "production" && !Array.isArray(storeEnhancers)) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
+  }
+  if (process.env.NODE_ENV !== "production" && storeEnhancers.some((item) => typeof item !== "function")) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
+  }
+  if (process.env.NODE_ENV !== "production" && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
+    console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
+  }
+  const composedEnhancer = finalCompose(...storeEnhancers);
+  return createStore(rootReducer, preloadedState, composedEnhancer);
+}
+
+// src/mapBuilders.ts
+function executeReducerBuilderCallback(builderCallback) {
+  const actionsMap = {};
+  const actionMatchers = [];
+  let defaultCaseReducer;
+  const builder = {
+    addCase(typeOrActionCreator, reducer) {
+      if (process.env.NODE_ENV !== "production") {
+        if (actionMatchers.length > 0) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
+        }
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
+      if (!type) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
+      }
+      if (type in actionsMap) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
+      }
+      actionsMap[type] = reducer;
+      return builder;
+    },
+    addAsyncThunk(asyncThunk, reducers) {
+      if (process.env.NODE_ENV !== "production") {
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(43) : "`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
+      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
+      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
+      if (reducers.settled) actionMatchers.push({
+        matcher: asyncThunk.settled,
+        reducer: reducers.settled
+      });
+      return builder;
+    },
+    addMatcher(matcher, reducer) {
+      if (process.env.NODE_ENV !== "production") {
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      actionMatchers.push({
+        matcher,
+        reducer
+      });
+      return builder;
+    },
+    addDefaultCase(reducer) {
+      if (process.env.NODE_ENV !== "production") {
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
+        }
+      }
+      defaultCaseReducer = reducer;
+      return builder;
+    }
+  };
+  builderCallback(builder);
+  return [actionsMap, actionMatchers, defaultCaseReducer];
+}
+
+// src/createReducer.ts
+function isStateFunction(x) {
+  return typeof x === "function";
+}
+function createReducer(initialState, mapOrBuilderCallback) {
+  if (process.env.NODE_ENV !== "production") {
+    if (typeof mapOrBuilderCallback === "object") {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
+    }
+  }
+  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
+  let getInitialState;
+  if (isStateFunction(initialState)) {
+    getInitialState = () => freezeDraftable(initialState());
+  } else {
+    const frozenInitialState = freezeDraftable(initialState);
+    getInitialState = () => frozenInitialState;
+  }
+  function reducer(state = getInitialState(), action) {
+    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
+      matcher
+    }) => matcher(action)).map(({
+      reducer: reducer2
+    }) => reducer2)];
+    if (caseReducers.filter((cr) => !!cr).length === 0) {
+      caseReducers = [finalDefaultCaseReducer];
+    }
+    return caseReducers.reduce((previousState, caseReducer) => {
+      if (caseReducer) {
+        if (isDraft(previousState)) {
+          const draft = previousState;
+          const result = caseReducer(draft, action);
+          if (result === void 0) {
+            return previousState;
+          }
+          return result;
+        } else if (!isDraftable(previousState)) {
+          const result = caseReducer(previousState, action);
+          if (result === void 0) {
+            if (previousState === null) {
+              return previousState;
+            }
+            throw Error("A case reducer on a non-draftable value must not return undefined");
+          }
+          return result;
+        } else {
+          return produce(previousState, (draft) => {
+            return caseReducer(draft, action);
+          });
+        }
+      }
+      return previousState;
+    }, state);
+  }
+  reducer.getInitialState = getInitialState;
+  return reducer;
+}
+
+// src/matchers.ts
+var matches = (matcher, action) => {
+  if (hasMatchFunction(matcher)) {
+    return matcher.match(action);
+  } else {
+    return matcher(action);
+  }
+};
+function isAnyOf(...matchers) {
+  return (action) => {
+    return matchers.some((matcher) => matches(matcher, action));
+  };
+}
+function isAllOf(...matchers) {
+  return (action) => {
+    return matchers.every((matcher) => matches(matcher, action));
+  };
+}
+function hasExpectedRequestMetadata(action, validStatus) {
+  if (!action || !action.meta) return false;
+  const hasValidRequestId = typeof action.meta.requestId === "string";
+  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
+  return hasValidRequestId && hasValidRequestStatus;
+}
+function isAsyncThunkArray(a) {
+  return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
+}
+function isPending(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["pending"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isPending()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
+}
+function isRejected(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejected()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
+}
+function isRejectedWithValue(...asyncThunks) {
+  const hasFlag = (action) => {
+    return action && action.meta && action.meta.rejectedWithValue;
+  };
+  if (asyncThunks.length === 0) {
+    return isAllOf(isRejected(...asyncThunks), hasFlag);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejectedWithValue()(asyncThunks[0]);
+  }
+  return isAllOf(isRejected(...asyncThunks), hasFlag);
+}
+function isFulfilled(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isFulfilled()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
+}
+function isAsyncThunkAction(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isAsyncThunkAction()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));
+}
+
+// src/nanoid.ts
+var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
+var nanoid = (size = 21) => {
+  let id = "";
+  let i = size;
+  while (i--) {
+    id += urlAlphabet[Math.random() * 64 | 0];
+  }
+  return id;
+};
+
+// src/createAsyncThunk.ts
+var commonProperties = ["name", "message", "stack", "code"];
+var RejectWithValue = class {
+  constructor(payload, meta) {
+    this.payload = payload;
+    this.meta = meta;
+    /*
+    type-only property to distinguish between RejectWithValue and FulfillWithMeta
+    does not exist at runtime
+    */
+    __publicField(this, "_type");
+  }
+};
+var FulfillWithMeta = class {
+  constructor(payload, meta) {
+    this.payload = payload;
+    this.meta = meta;
+    /*
+    type-only property to distinguish between RejectWithValue and FulfillWithMeta
+    does not exist at runtime
+    */
+    __publicField(this, "_type");
+  }
+};
+var miniSerializeError = (value) => {
+  if (typeof value === "object" && value !== null) {
+    const simpleError = {};
+    for (const property of commonProperties) {
+      if (typeof value[property] === "string") {
+        simpleError[property] = value[property];
+      }
+    }
+    return simpleError;
+  }
+  return {
+    message: String(value)
+  };
+};
+var externalAbortMessage = "External signal was aborted";
+var createAsyncThunk = /* @__PURE__ */ (() => {
+  function createAsyncThunk2(typePrefix, payloadCreator, options) {
+    const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
+      payload,
+      meta: __spreadProps(__spreadValues({}, meta || {}), {
+        arg,
+        requestId,
+        requestStatus: "fulfilled"
+      })
+    }));
+    const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
+      payload: void 0,
+      meta: __spreadProps(__spreadValues({}, meta || {}), {
+        arg,
+        requestId,
+        requestStatus: "pending"
+      })
+    }));
+    const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
+      payload,
+      error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
+      meta: __spreadProps(__spreadValues({}, meta || {}), {
+        arg,
+        requestId,
+        rejectedWithValue: !!payload,
+        requestStatus: "rejected",
+        aborted: (error == null ? void 0 : error.name) === "AbortError",
+        condition: (error == null ? void 0 : error.name) === "ConditionError"
+      })
+    }));
+    function actionCreator(arg, {
+      signal
+    } = {}) {
+      return (dispatch, getState, extra) => {
+        const requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
+        const abortController = new AbortController();
+        let abortHandler;
+        let abortReason;
+        function abort(reason) {
+          abortReason = reason;
+          abortController.abort();
+        }
+        if (signal) {
+          if (signal.aborted) {
+            abort(externalAbortMessage);
+          } else {
+            signal.addEventListener("abort", () => abort(externalAbortMessage), {
+              once: true
+            });
+          }
+        }
+        const promise = async function() {
+          var _a, _b;
+          let finalAction;
+          try {
+            let conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, {
+              getState,
+              extra
+            });
+            if (isThenable(conditionResult)) {
+              conditionResult = await conditionResult;
+            }
+            if (conditionResult === false || abortController.signal.aborted) {
+              throw {
+                name: "ConditionError",
+                message: "Aborted due to condition callback returning false."
+              };
+            }
+            const abortedPromise = new Promise((_, reject) => {
+              abortHandler = () => {
+                reject({
+                  name: "AbortError",
+                  message: abortReason || "Aborted"
+                });
+              };
+              abortController.signal.addEventListener("abort", abortHandler, {
+                once: true
+              });
+            });
+            dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, {
+              requestId,
+              arg
+            }, {
+              getState,
+              extra
+            })));
+            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
+              dispatch,
+              getState,
+              extra,
+              requestId,
+              signal: abortController.signal,
+              abort,
+              rejectWithValue: (value, meta) => {
+                return new RejectWithValue(value, meta);
+              },
+              fulfillWithValue: (value, meta) => {
+                return new FulfillWithMeta(value, meta);
+              }
+            })).then((result) => {
+              if (result instanceof RejectWithValue) {
+                throw result;
+              }
+              if (result instanceof FulfillWithMeta) {
+                return fulfilled(result.payload, requestId, arg, result.meta);
+              }
+              return fulfilled(result, requestId, arg);
+            })]);
+          } catch (err) {
+            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
+          } finally {
+            if (abortHandler) {
+              abortController.signal.removeEventListener("abort", abortHandler);
+            }
+          }
+          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
+          if (!skipDispatch) {
+            dispatch(finalAction);
+          }
+          return finalAction;
+        }();
+        return Object.assign(promise, {
+          abort,
+          requestId,
+          arg,
+          unwrap() {
+            return promise.then(unwrapResult);
+          }
+        });
+      };
+    }
+    return Object.assign(actionCreator, {
+      pending,
+      rejected,
+      fulfilled,
+      settled: isAnyOf(rejected, fulfilled),
+      typePrefix
+    });
+  }
+  createAsyncThunk2.withTypes = () => createAsyncThunk2;
+  return createAsyncThunk2;
+})();
+function unwrapResult(action) {
+  if (action.meta && action.meta.rejectedWithValue) {
+    throw action.payload;
+  }
+  if (action.error) {
+    throw action.error;
+  }
+  return action.payload;
+}
+function isThenable(value) {
+  return value !== null && typeof value === "object" && typeof value.then === "function";
+}
+
+// src/createSlice.ts
+var asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
+var asyncThunkCreator = {
+  [asyncThunkSymbol]: createAsyncThunk
+};
+var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
+  ReducerType2["reducer"] = "reducer";
+  ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
+  ReducerType2["asyncThunk"] = "asyncThunk";
+  return ReducerType2;
+})(ReducerType || {});
+function getType(slice, actionKey) {
+  return `${slice}/${actionKey}`;
+}
+function buildCreateSlice({
+  creators
+} = {}) {
+  var _a;
+  const cAT = (_a = creators == null ? void 0 : creators.asyncThunk) == null ? void 0 : _a[asyncThunkSymbol];
+  return function createSlice2(options) {
+    const {
+      name,
+      reducerPath = name
+    } = options;
+    if (!name) {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
+    }
+    if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+      if (options.initialState === void 0) {
+        console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
+      }
+    }
+    const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
+    const reducerNames = Object.keys(reducers);
+    const context = {
+      sliceCaseReducersByName: {},
+      sliceCaseReducersByType: {},
+      actionCreators: {},
+      sliceMatchers: []
+    };
+    const contextMethods = {
+      addCase(typeOrActionCreator, reducer2) {
+        const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
+        if (!type) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
+        }
+        if (type in context.sliceCaseReducersByType) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
+        }
+        context.sliceCaseReducersByType[type] = reducer2;
+        return contextMethods;
+      },
+      addMatcher(matcher, reducer2) {
+        context.sliceMatchers.push({
+          matcher,
+          reducer: reducer2
+        });
+        return contextMethods;
+      },
+      exposeAction(name2, actionCreator) {
+        context.actionCreators[name2] = actionCreator;
+        return contextMethods;
+      },
+      exposeCaseReducer(name2, reducer2) {
+        context.sliceCaseReducersByName[name2] = reducer2;
+        return contextMethods;
+      }
+    };
+    reducerNames.forEach((reducerName) => {
+      const reducerDefinition = reducers[reducerName];
+      const reducerDetails = {
+        reducerName,
+        type: getType(name, reducerName),
+        createNotation: typeof options.reducers === "function"
+      };
+      if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
+        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
+      } else {
+        handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
+      }
+    });
+    function buildReducer() {
+      if (process.env.NODE_ENV !== "production") {
+        if (typeof options.extraReducers === "object") {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
+        }
+      }
+      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
+      const finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), context.sliceCaseReducersByType);
+      return createReducer(options.initialState, (builder) => {
+        for (let key in finalCaseReducers) {
+          builder.addCase(key, finalCaseReducers[key]);
+        }
+        for (let sM of context.sliceMatchers) {
+          builder.addMatcher(sM.matcher, sM.reducer);
+        }
+        for (let m of actionMatchers) {
+          builder.addMatcher(m.matcher, m.reducer);
+        }
+        if (defaultCaseReducer) {
+          builder.addDefaultCase(defaultCaseReducer);
+        }
+      });
+    }
+    const selectSelf = (state) => state;
+    const injectedSelectorCache = /* @__PURE__ */ new Map();
+    const injectedStateCache = /* @__PURE__ */ new WeakMap();
+    let _reducer;
+    function reducer(state, action) {
+      if (!_reducer) _reducer = buildReducer();
+      return _reducer(state, action);
+    }
+    function getInitialState() {
+      if (!_reducer) _reducer = buildReducer();
+      return _reducer.getInitialState();
+    }
+    function makeSelectorProps(reducerPath2, injected = false) {
+      function selectSlice(state) {
+        let sliceState = state[reducerPath2];
+        if (typeof sliceState === "undefined") {
+          if (injected) {
+            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);
+          } else if (process.env.NODE_ENV !== "production") {
+            throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
+          }
+        }
+        return sliceState;
+      }
+      function getSelectors(selectState = selectSelf) {
+        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => /* @__PURE__ */ new WeakMap());
+        return getOrInsertComputed(selectorCache, selectState, () => {
+          var _a2;
+          const map = {};
+          for (const [name2, selector] of Object.entries((_a2 = options.selectors) != null ? _a2 : {})) {
+            map[name2] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);
+          }
+          return map;
+        });
+      }
+      return {
+        reducerPath: reducerPath2,
+        getSelectors,
+        get selectors() {
+          return getSelectors(selectSlice);
+        },
+        selectSlice
+      };
+    }
+    const slice = __spreadProps(__spreadValues({
+      name,
+      reducer,
+      actions: context.actionCreators,
+      caseReducers: context.sliceCaseReducersByName,
+      getInitialState
+    }, makeSelectorProps(reducerPath)), {
+      injectInto(injectable, _a2 = {}) {
+        var _b = _a2, {
+          reducerPath: pathOpt
+        } = _b, config = __objRest(_b, [
+          "reducerPath"
+        ]);
+        const newReducerPath = pathOpt != null ? pathOpt : reducerPath;
+        injectable.inject({
+          reducerPath: newReducerPath,
+          reducer
+        }, config);
+        return __spreadValues(__spreadValues({}, slice), makeSelectorProps(newReducerPath, true));
+      }
+    });
+    return slice;
+  };
+}
+function wrapSelector(selector, selectState, getInitialState, injected) {
+  function wrapper(rootState, ...args) {
+    let sliceState = selectState(rootState);
+    if (typeof sliceState === "undefined") {
+      if (injected) {
+        sliceState = getInitialState();
+      } else if (process.env.NODE_ENV !== "production") {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
+      }
+    }
+    return selector(sliceState, ...args);
+  }
+  wrapper.unwrapped = selector;
+  return wrapper;
+}
+var createSlice = /* @__PURE__ */ buildCreateSlice();
+function buildReducerCreators() {
+  function asyncThunk(payloadCreator, config) {
+    return __spreadValues({
+      _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
+      payloadCreator
+    }, config);
+  }
+  asyncThunk.withTypes = () => asyncThunk;
+  return {
+    reducer(caseReducer) {
+      return Object.assign({
+        // hack so the wrapping function has the same name as the original
+        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
+        [caseReducer.name](...args) {
+          return caseReducer(...args);
+        }
+      }[caseReducer.name], {
+        _reducerDefinitionType: "reducer" /* reducer */
+      });
+    },
+    preparedReducer(prepare, reducer) {
+      return {
+        _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
+        prepare,
+        reducer
+      };
+    },
+    asyncThunk
+  };
+}
+function handleNormalReducerDefinition({
+  type,
+  reducerName,
+  createNotation
+}, maybeReducerWithPrepare, context) {
+  let caseReducer;
+  let prepareCallback;
+  if ("reducer" in maybeReducerWithPrepare) {
+    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
+    }
+    caseReducer = maybeReducerWithPrepare.reducer;
+    prepareCallback = maybeReducerWithPrepare.prepare;
+  } else {
+    caseReducer = maybeReducerWithPrepare;
+  }
+  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
+}
+function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
+  return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
+}
+function isCaseReducerWithPrepareDefinition(reducerDefinition) {
+  return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
+}
+function handleThunkCaseReducerDefinition({
+  type,
+  reducerName
+}, reducerDefinition, context, cAT) {
+  if (!cAT) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
+  }
+  const {
+    payloadCreator,
+    fulfilled,
+    pending,
+    rejected,
+    settled,
+    options
+  } = reducerDefinition;
+  const thunk = cAT(type, payloadCreator, options);
+  context.exposeAction(reducerName, thunk);
+  if (fulfilled) {
+    context.addCase(thunk.fulfilled, fulfilled);
+  }
+  if (pending) {
+    context.addCase(thunk.pending, pending);
+  }
+  if (rejected) {
+    context.addCase(thunk.rejected, rejected);
+  }
+  if (settled) {
+    context.addMatcher(thunk.settled, settled);
+  }
+  context.exposeCaseReducer(reducerName, {
+    fulfilled: fulfilled || noop,
+    pending: pending || noop,
+    rejected: rejected || noop,
+    settled: settled || noop
+  });
+}
+function noop() {
+}
+
+// src/entities/entity_state.ts
+function getInitialEntityState() {
+  return {
+    ids: [],
+    entities: {}
+  };
+}
+function createInitialStateFactory(stateAdapter) {
+  function getInitialState(additionalState = {}, entities) {
+    const state = Object.assign(getInitialEntityState(), additionalState);
+    return entities ? stateAdapter.setAll(state, entities) : state;
+  }
+  return {
+    getInitialState
+  };
+}
+
+// src/entities/state_selectors.ts
+function createSelectorsFactory() {
+  function getSelectors(selectState, options = {}) {
+    const {
+      createSelector: createSelector2 = createDraftSafeSelector
+    } = options;
+    const selectIds = (state) => state.ids;
+    const selectEntities = (state) => state.entities;
+    const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
+    const selectId = (_, id) => id;
+    const selectById = (entities, id) => entities[id];
+    const selectTotal = createSelector2(selectIds, (ids) => ids.length);
+    if (!selectState) {
+      return {
+        selectIds,
+        selectEntities,
+        selectAll,
+        selectTotal,
+        selectById: createSelector2(selectEntities, selectId, selectById)
+      };
+    }
+    const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
+    return {
+      selectIds: createSelector2(selectState, selectIds),
+      selectEntities: selectGlobalizedEntities,
+      selectAll: createSelector2(selectState, selectAll),
+      selectTotal: createSelector2(selectState, selectTotal),
+      selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
+    };
+  }
+  return {
+    getSelectors
+  };
+}
+
+// src/entities/state_adapter.ts
+var isDraftTyped = isDraft;
+function createSingleArgumentStateOperator(mutator) {
+  const operator = createStateOperator((_, state) => mutator(state));
+  return function operation(state) {
+    return operator(state, void 0);
+  };
+}
+function createStateOperator(mutator) {
+  return function operation(state, arg) {
+    function isPayloadActionArgument(arg2) {
+      return isFSA(arg2);
+    }
+    const runMutator = (draft) => {
+      if (isPayloadActionArgument(arg)) {
+        mutator(arg.payload, draft);
+      } else {
+        mutator(arg, draft);
+      }
+    };
+    if (isDraftTyped(state)) {
+      runMutator(state);
+      return state;
+    }
+    return produce(state, runMutator);
+  };
+}
+
+// src/entities/utils.ts
+function selectIdValue(entity, selectId) {
+  const key = selectId(entity);
+  if (process.env.NODE_ENV !== "production" && key === void 0) {
+    console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
+  }
+  return key;
+}
+function ensureEntitiesArray(entities) {
+  if (!Array.isArray(entities)) {
+    entities = Object.values(entities);
+  }
+  return entities;
+}
+function getCurrent(value) {
+  return isDraft(value) ? current(value) : value;
+}
+function splitAddedUpdatedEntities(newEntities, selectId, state) {
+  newEntities = ensureEntitiesArray(newEntities);
+  const existingIdsArray = getCurrent(state.ids);
+  const existingIds = new Set(existingIdsArray);
+  const added = [];
+  const addedIds = /* @__PURE__ */ new Set([]);
+  const updated = [];
+  for (const entity of newEntities) {
+    const id = selectIdValue(entity, selectId);
+    if (existingIds.has(id) || addedIds.has(id)) {
+      updated.push({
+        id,
+        changes: entity
+      });
+    } else {
+      addedIds.add(id);
+      added.push(entity);
+    }
+  }
+  return [added, updated, existingIdsArray];
+}
+
+// src/entities/unsorted_state_adapter.ts
+function createUnsortedStateAdapter(selectId) {
+  function addOneMutably(entity, state) {
+    const key = selectIdValue(entity, selectId);
+    if (key in state.entities) {
+      return;
+    }
+    state.ids.push(key);
+    state.entities[key] = entity;
+  }
+  function addManyMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    for (const entity of newEntities) {
+      addOneMutably(entity, state);
+    }
+  }
+  function setOneMutably(entity, state) {
+    const key = selectIdValue(entity, selectId);
+    if (!(key in state.entities)) {
+      state.ids.push(key);
+    }
+    ;
+    state.entities[key] = entity;
+  }
+  function setManyMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    for (const entity of newEntities) {
+      setOneMutably(entity, state);
+    }
+  }
+  function setAllMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    state.ids = [];
+    state.entities = {};
+    addManyMutably(newEntities, state);
+  }
+  function removeOneMutably(key, state) {
+    return removeManyMutably([key], state);
+  }
+  function removeManyMutably(keys, state) {
+    let didMutate = false;
+    keys.forEach((key) => {
+      if (key in state.entities) {
+        delete state.entities[key];
+        didMutate = true;
+      }
+    });
+    if (didMutate) {
+      state.ids = state.ids.filter((id) => id in state.entities);
+    }
+  }
+  function removeAllMutably(state) {
+    Object.assign(state, {
+      ids: [],
+      entities: {}
+    });
+  }
+  function takeNewKey(keys, update, state) {
+    const original3 = state.entities[update.id];
+    if (original3 === void 0) {
+      return false;
+    }
+    const updated = Object.assign({}, original3, update.changes);
+    const newKey = selectIdValue(updated, selectId);
+    const hasNewKey = newKey !== update.id;
+    if (hasNewKey) {
+      keys[update.id] = newKey;
+      delete state.entities[update.id];
+    }
+    ;
+    state.entities[newKey] = updated;
+    return hasNewKey;
+  }
+  function updateOneMutably(update, state) {
+    return updateManyMutably([update], state);
+  }
+  function updateManyMutably(updates, state) {
+    const newKeys = {};
+    const updatesPerEntity = {};
+    updates.forEach((update) => {
+      var _a;
+      if (update.id in state.entities) {
+        updatesPerEntity[update.id] = {
+          id: update.id,
+          // Spreads ignore falsy values, so this works even if there isn't
+          // an existing update already at this key
+          changes: __spreadValues(__spreadValues({}, (_a = updatesPerEntity[update.id]) == null ? void 0 : _a.changes), update.changes)
+        };
+      }
+    });
+    updates = Object.values(updatesPerEntity);
+    const didMutateEntities = updates.length > 0;
+    if (didMutateEntities) {
+      const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
+      if (didMutateIds) {
+        state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
+      }
+    }
+  }
+  function upsertOneMutably(entity, state) {
+    return upsertManyMutably([entity], state);
+  }
+  function upsertManyMutably(newEntities, state) {
+    const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
+    addManyMutably(added, state);
+    updateManyMutably(updated, state);
+  }
+  return {
+    removeAll: createSingleArgumentStateOperator(removeAllMutably),
+    addOne: createStateOperator(addOneMutably),
+    addMany: createStateOperator(addManyMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+    removeOne: createStateOperator(removeOneMutably),
+    removeMany: createStateOperator(removeManyMutably)
+  };
+}
+
+// src/entities/sorted_state_adapter.ts
+function findInsertIndex(sortedItems, item, comparisonFunction) {
+  let lowIndex = 0;
+  let highIndex = sortedItems.length;
+  while (lowIndex < highIndex) {
+    let middleIndex = lowIndex + highIndex >>> 1;
+    const currentItem = sortedItems[middleIndex];
+    const res = comparisonFunction(item, currentItem);
+    if (res >= 0) {
+      lowIndex = middleIndex + 1;
+    } else {
+      highIndex = middleIndex;
+    }
+  }
+  return lowIndex;
+}
+function insert(sortedItems, item, comparisonFunction) {
+  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
+  sortedItems.splice(insertAtIndex, 0, item);
+  return sortedItems;
+}
+function createSortedStateAdapter(selectId, comparer) {
+  const {
+    removeOne,
+    removeMany,
+    removeAll
+  } = createUnsortedStateAdapter(selectId);
+  function addOneMutably(entity, state) {
+    return addManyMutably([entity], state);
+  }
+  function addManyMutably(newEntities, state, existingIds) {
+    newEntities = ensureEntitiesArray(newEntities);
+    const existingKeys = new Set(existingIds != null ? existingIds : getCurrent(state.ids));
+    const addedKeys = /* @__PURE__ */ new Set();
+    const models = newEntities.filter((model) => {
+      const modelId = selectIdValue(model, selectId);
+      const notAdded = !addedKeys.has(modelId);
+      if (notAdded) addedKeys.add(modelId);
+      return !existingKeys.has(modelId) && notAdded;
+    });
+    if (models.length !== 0) {
+      mergeFunction(state, models);
+    }
+  }
+  function setOneMutably(entity, state) {
+    return setManyMutably([entity], state);
+  }
+  function setManyMutably(newEntities, state) {
+    let deduplicatedEntities = {};
+    newEntities = ensureEntitiesArray(newEntities);
+    if (newEntities.length !== 0) {
+      for (const item of newEntities) {
+        const entityId = selectId(item);
+        deduplicatedEntities[entityId] = item;
+        delete state.entities[entityId];
+      }
+      newEntities = ensureEntitiesArray(deduplicatedEntities);
+      mergeFunction(state, newEntities);
+    }
+  }
+  function setAllMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    state.entities = {};
+    state.ids = [];
+    addManyMutably(newEntities, state, []);
+  }
+  function updateOneMutably(update, state) {
+    return updateManyMutably([update], state);
+  }
+  function updateManyMutably(updates, state) {
+    let appliedUpdates = false;
+    let replacedIds = false;
+    for (let update of updates) {
+      const entity = state.entities[update.id];
+      if (!entity) {
+        continue;
+      }
+      appliedUpdates = true;
+      Object.assign(entity, update.changes);
+      const newId = selectId(entity);
+      if (update.id !== newId) {
+        replacedIds = true;
+        delete state.entities[update.id];
+        const oldIndex = state.ids.indexOf(update.id);
+        state.ids[oldIndex] = newId;
+        state.entities[newId] = entity;
+      }
+    }
+    if (appliedUpdates) {
+      mergeFunction(state, [], appliedUpdates, replacedIds);
+    }
+  }
+  function upsertOneMutably(entity, state) {
+    return upsertManyMutably([entity], state);
+  }
+  function upsertManyMutably(newEntities, state) {
+    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
+    if (added.length) {
+      addManyMutably(added, state, existingIdsArray);
+    }
+    if (updated.length) {
+      updateManyMutably(updated, state);
+    }
+  }
+  function areArraysEqual(a, b) {
+    if (a.length !== b.length) {
+      return false;
+    }
+    for (let i = 0; i < a.length; i++) {
+      if (a[i] === b[i]) {
+        continue;
+      }
+      return false;
+    }
+    return true;
+  }
+  const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {
+    const currentEntities = getCurrent(state.entities);
+    const currentIds = getCurrent(state.ids);
+    const stateEntities = state.entities;
+    let ids = currentIds;
+    if (replacedIds) {
+      ids = new Set(currentIds);
+    }
+    let sortedEntities = [];
+    for (const id of ids) {
+      const entity = currentEntities[id];
+      if (entity) {
+        sortedEntities.push(entity);
+      }
+    }
+    const wasPreviouslyEmpty = sortedEntities.length === 0;
+    for (const item of addedItems) {
+      stateEntities[selectId(item)] = item;
+      if (!wasPreviouslyEmpty) {
+        insert(sortedEntities, item, comparer);
+      }
+    }
+    if (wasPreviouslyEmpty) {
+      sortedEntities = addedItems.slice().sort(comparer);
+    } else if (appliedUpdates) {
+      sortedEntities.sort(comparer);
+    }
+    const newSortedIds = sortedEntities.map(selectId);
+    if (!areArraysEqual(currentIds, newSortedIds)) {
+      state.ids = newSortedIds;
+    }
+  };
+  return {
+    removeOne,
+    removeMany,
+    removeAll,
+    addOne: createStateOperator(addOneMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    addMany: createStateOperator(addManyMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertMany: createStateOperator(upsertManyMutably)
+  };
+}
+
+// src/entities/create_adapter.ts
+function createEntityAdapter(options = {}) {
+  const {
+    selectId,
+    sortComparer
+  } = __spreadValues({
+    sortComparer: false,
+    selectId: (instance) => instance.id
+  }, options);
+  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
+  const stateFactory = createInitialStateFactory(stateAdapter);
+  const selectorsFactory = createSelectorsFactory();
+  return __spreadValues(__spreadValues(__spreadValues({
+    selectId,
+    sortComparer
+  }, stateFactory), selectorsFactory), stateAdapter);
+}
+
+// src/listenerMiddleware/exceptions.ts
+var task = "task";
+var listener = "listener";
+var completed = "completed";
+var cancelled = "cancelled";
+var taskCancelled = `task-${cancelled}`;
+var taskCompleted = `task-${completed}`;
+var listenerCancelled = `${listener}-${cancelled}`;
+var listenerCompleted = `${listener}-${completed}`;
+var TaskAbortError = class {
+  constructor(code) {
+    this.code = code;
+    __publicField(this, "name", "TaskAbortError");
+    __publicField(this, "message");
+    this.message = `${task} ${cancelled} (reason: ${code})`;
+  }
+};
+
+// src/listenerMiddleware/utils.ts
+var assertFunction = (func, expected) => {
+  if (typeof func !== "function") {
+    throw new TypeError(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
+  }
+};
+var noop2 = () => {
+};
+var catchRejection = (promise, onError = noop2) => {
+  promise.catch(onError);
+  return promise;
+};
+var addAbortSignalListener = (abortSignal, callback) => {
+  abortSignal.addEventListener("abort", callback, {
+    once: true
+  });
+  return () => abortSignal.removeEventListener("abort", callback);
+};
+
+// src/listenerMiddleware/task.ts
+var validateActive = (signal) => {
+  if (signal.aborted) {
+    throw new TaskAbortError(signal.reason);
+  }
+};
+function raceWithSignal(signal, promise) {
+  let cleanup = noop2;
+  return new Promise((resolve, reject) => {
+    const notifyRejection = () => reject(new TaskAbortError(signal.reason));
+    if (signal.aborted) {
+      notifyRejection();
+      return;
+    }
+    cleanup = addAbortSignalListener(signal, notifyRejection);
+    promise.finally(() => cleanup()).then(resolve, reject);
+  }).finally(() => {
+    cleanup = noop2;
+  });
+}
+var runTask = async (task2, cleanUp) => {
+  try {
+    await Promise.resolve();
+    const value = await task2();
+    return {
+      status: "ok",
+      value
+    };
+  } catch (error) {
+    return {
+      status: error instanceof TaskAbortError ? "cancelled" : "rejected",
+      error
+    };
+  } finally {
+    cleanUp == null ? void 0 : cleanUp();
+  }
+};
+var createPause = (signal) => {
+  return (promise) => {
+    return catchRejection(raceWithSignal(signal, promise).then((output) => {
+      validateActive(signal);
+      return output;
+    }));
+  };
+};
+var createDelay = (signal) => {
+  const pause = createPause(signal);
+  return (timeoutMs) => {
+    return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
+  };
+};
+
+// src/listenerMiddleware/index.ts
+var {
+  assign
+} = Object;
+var INTERNAL_NIL_TOKEN = {};
+var alm = "listenerMiddleware";
+var createFork = (parentAbortSignal, parentBlockingPromises) => {
+  const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));
+  return (taskExecutor, opts) => {
+    assertFunction(taskExecutor, "taskExecutor");
+    const childAbortController = new AbortController();
+    linkControllers(childAbortController);
+    const result = runTask(async () => {
+      validateActive(parentAbortSignal);
+      validateActive(childAbortController.signal);
+      const result2 = await taskExecutor({
+        pause: createPause(childAbortController.signal),
+        delay: createDelay(childAbortController.signal),
+        signal: childAbortController.signal
+      });
+      validateActive(childAbortController.signal);
+      return result2;
+    }, () => childAbortController.abort(taskCompleted));
+    if (opts == null ? void 0 : opts.autoJoin) {
+      parentBlockingPromises.push(result.catch(noop2));
+    }
+    return {
+      result: createPause(parentAbortSignal)(result),
+      cancel() {
+        childAbortController.abort(taskCancelled);
+      }
+    };
+  };
+};
+var createTakePattern = (startListening, signal) => {
+  const take = async (predicate, timeout) => {
+    validateActive(signal);
+    let unsubscribe = () => {
+    };
+    const tuplePromise = new Promise((resolve, reject) => {
+      let stopListening = startListening({
+        predicate,
+        effect: (action, listenerApi) => {
+          listenerApi.unsubscribe();
+          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
+        }
+      });
+      unsubscribe = () => {
+        stopListening();
+        reject();
+      };
+    });
+    const promises = [tuplePromise];
+    if (timeout != null) {
+      promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
+    }
+    try {
+      const output = await raceWithSignal(signal, Promise.race(promises));
+      validateActive(signal);
+      return output;
+    } finally {
+      unsubscribe();
+    }
+  };
+  return (predicate, timeout) => catchRejection(take(predicate, timeout));
+};
+var getListenerEntryPropsFrom = (options) => {
+  let {
+    type,
+    actionCreator,
+    matcher,
+    predicate,
+    effect
+  } = options;
+  if (type) {
+    predicate = createAction(type).match;
+  } else if (actionCreator) {
+    type = actionCreator.type;
+    predicate = actionCreator.match;
+  } else if (matcher) {
+    predicate = matcher;
+  } else if (predicate) {
+  } else {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
+  }
+  assertFunction(effect, "options.listener");
+  return {
+    predicate,
+    type,
+    effect
+  };
+};
+var createListenerEntry = /* @__PURE__ */ assign((options) => {
+  const {
+    type,
+    predicate,
+    effect
+  } = getListenerEntryPropsFrom(options);
+  const entry = {
+    id: nanoid(),
+    effect,
+    type,
+    predicate,
+    pending: /* @__PURE__ */ new Set(),
+    unsubscribe: () => {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
+    }
+  };
+  return entry;
+}, {
+  withTypes: () => createListenerEntry
+});
+var findListenerEntry = (listenerMap, options) => {
+  const {
+    type,
+    effect,
+    predicate
+  } = getListenerEntryPropsFrom(options);
+  return Array.from(listenerMap.values()).find((entry) => {
+    const matchPredicateOrType = typeof type === "string" ? entry.type === type : entry.predicate === predicate;
+    return matchPredicateOrType && entry.effect === effect;
+  });
+};
+var cancelActiveListeners = (entry) => {
+  entry.pending.forEach((controller) => {
+    controller.abort(listenerCancelled);
+  });
+};
+var createClearListenerMiddleware = (listenerMap, executingListeners) => {
+  return () => {
+    for (const listener2 of executingListeners.keys()) {
+      cancelActiveListeners(listener2);
+    }
+    listenerMap.clear();
+  };
+};
+var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
+  try {
+    errorHandler(errorToNotify, errorInfo);
+  } catch (errorHandlerError) {
+    setTimeout(() => {
+      throw errorHandlerError;
+    }, 0);
+  }
+};
+var addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), {
+  withTypes: () => addListener
+});
+var clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
+var removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), {
+  withTypes: () => removeListener
+});
+var defaultErrorHandler = (...args) => {
+  console.error(`${alm}/error`, ...args);
+};
+var createListenerMiddleware = (middlewareOptions = {}) => {
+  const listenerMap = /* @__PURE__ */ new Map();
+  const executingListeners = /* @__PURE__ */ new Map();
+  const trackExecutingListener = (entry) => {
+    var _a;
+    const count = (_a = executingListeners.get(entry)) != null ? _a : 0;
+    executingListeners.set(entry, count + 1);
+  };
+  const untrackExecutingListener = (entry) => {
+    var _a;
+    const count = (_a = executingListeners.get(entry)) != null ? _a : 1;
+    if (count === 1) {
+      executingListeners.delete(entry);
+    } else {
+      executingListeners.set(entry, count - 1);
+    }
+  };
+  const {
+    extra,
+    onError = defaultErrorHandler
+  } = middlewareOptions;
+  assertFunction(onError, "onError");
+  const insertEntry = (entry) => {
+    entry.unsubscribe = () => listenerMap.delete(entry.id);
+    listenerMap.set(entry.id, entry);
+    return (cancelOptions) => {
+      entry.unsubscribe();
+      if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {
+        cancelActiveListeners(entry);
+      }
+    };
+  };
+  const startListening = (options) => {
+    var _a;
+    const entry = (_a = findListenerEntry(listenerMap, options)) != null ? _a : createListenerEntry(options);
+    return insertEntry(entry);
+  };
+  assign(startListening, {
+    withTypes: () => startListening
+  });
+  const stopListening = (options) => {
+    const entry = findListenerEntry(listenerMap, options);
+    if (entry) {
+      entry.unsubscribe();
+      if (options.cancelActive) {
+        cancelActiveListeners(entry);
+      }
+    }
+    return !!entry;
+  };
+  assign(stopListening, {
+    withTypes: () => stopListening
+  });
+  const notifyListener = async (entry, action, api, getOriginalState) => {
+    const internalTaskController = new AbortController();
+    const take = createTakePattern(startListening, internalTaskController.signal);
+    const autoJoinPromises = [];
+    try {
+      entry.pending.add(internalTaskController);
+      trackExecutingListener(entry);
+      await Promise.resolve(entry.effect(
+        action,
+        // Use assign() rather than ... to avoid extra helper functions added to bundle
+        assign({}, api, {
+          getOriginalState,
+          condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
+          take,
+          delay: createDelay(internalTaskController.signal),
+          pause: createPause(internalTaskController.signal),
+          extra,
+          signal: internalTaskController.signal,
+          fork: createFork(internalTaskController.signal, autoJoinPromises),
+          unsubscribe: entry.unsubscribe,
+          subscribe: () => {
+            listenerMap.set(entry.id, entry);
+          },
+          cancelActiveListeners: () => {
+            entry.pending.forEach((controller, _, set) => {
+              if (controller !== internalTaskController) {
+                controller.abort(listenerCancelled);
+                set.delete(controller);
+              }
+            });
+          },
+          cancel: () => {
+            internalTaskController.abort(listenerCancelled);
+            entry.pending.delete(internalTaskController);
+          },
+          throwIfCancelled: () => {
+            validateActive(internalTaskController.signal);
+          }
+        })
+      ));
+    } catch (listenerError) {
+      if (!(listenerError instanceof TaskAbortError)) {
+        safelyNotifyError(onError, listenerError, {
+          raisedBy: "effect"
+        });
+      }
+    } finally {
+      await Promise.all(autoJoinPromises);
+      internalTaskController.abort(listenerCompleted);
+      untrackExecutingListener(entry);
+      entry.pending.delete(internalTaskController);
+    }
+  };
+  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);
+  const middleware = (api) => (next) => (action) => {
+    if (!isAction(action)) {
+      return next(action);
+    }
+    if (addListener.match(action)) {
+      return startListening(action.payload);
+    }
+    if (clearAllListeners.match(action)) {
+      clearListenerMiddleware();
+      return;
+    }
+    if (removeListener.match(action)) {
+      return stopListening(action.payload);
+    }
+    let originalState = api.getState();
+    const getOriginalState = () => {
+      if (originalState === INTERNAL_NIL_TOKEN) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
+      }
+      return originalState;
+    };
+    let result;
+    try {
+      result = next(action);
+      if (listenerMap.size > 0) {
+        const currentState = api.getState();
+        const listenerEntries = Array.from(listenerMap.values());
+        for (const entry of listenerEntries) {
+          let runListener = false;
+          try {
+            runListener = entry.predicate(action, currentState, originalState);
+          } catch (predicateError) {
+            runListener = false;
+            safelyNotifyError(onError, predicateError, {
+              raisedBy: "predicate"
+            });
+          }
+          if (!runListener) {
+            continue;
+          }
+          notifyListener(entry, action, api, getOriginalState);
+        }
+      }
+    } finally {
+      originalState = INTERNAL_NIL_TOKEN;
+    }
+    return result;
+  };
+  return {
+    middleware,
+    startListening,
+    stopListening,
+    clearListeners: clearListenerMiddleware
+  };
+};
+
+// src/dynamicMiddleware/index.ts
+var createMiddlewareEntry = (middleware) => ({
+  middleware,
+  applied: /* @__PURE__ */ new Map()
+});
+var matchInstance = (instanceId) => (action) => {
+  var _a;
+  return ((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.instanceId) === instanceId;
+};
+var createDynamicMiddleware = () => {
+  const instanceId = nanoid();
+  const middlewareMap = /* @__PURE__ */ new Map();
+  const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
+    payload: middlewares,
+    meta: {
+      instanceId
+    }
+  })), {
+    withTypes: () => withMiddleware
+  });
+  const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
+    middlewares.forEach((middleware2) => {
+      getOrInsertComputed(middlewareMap, middleware2, createMiddlewareEntry);
+    });
+  }, {
+    withTypes: () => addMiddleware
+  });
+  const getFinalMiddleware = (api) => {
+    const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => getOrInsertComputed(entry.applied, api, entry.middleware));
+    return compose(...appliedMiddleware);
+  };
+  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
+  const middleware = (api) => (next) => (action) => {
+    if (isWithMiddleware(action)) {
+      addMiddleware(...action.payload);
+      return api.dispatch;
+    }
+    return getFinalMiddleware(api)(next)(action);
+  };
+  return {
+    middleware,
+    addMiddleware,
+    withMiddleware,
+    instanceId
+  };
+};
+
+// src/combineSlices.ts
+import { combineReducers as combineReducers2 } from "redux";
+var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
+var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
+var ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
+var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
+var stateProxyMap = /* @__PURE__ */ new WeakMap();
+var createStateProxy = (state, reducerMap, initialStateCache) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {
+  get: (target, prop, receiver) => {
+    if (prop === ORIGINAL_STATE) return target;
+    const result = Reflect.get(target, prop, receiver);
+    if (typeof result === "undefined") {
+      const cached = initialStateCache[prop];
+      if (typeof cached !== "undefined") return cached;
+      const reducer = reducerMap[prop];
+      if (reducer) {
+        const reducerResult = reducer(void 0, {
+          type: nanoid()
+        });
+        if (typeof reducerResult === "undefined") {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
+        }
+        initialStateCache[prop] = reducerResult;
+        return reducerResult;
+      }
+    }
+    return result;
+  }
+}));
+var original = (state) => {
+  if (!isStateProxy(state)) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
+  }
+  return state[ORIGINAL_STATE];
+};
+var emptyObject = {};
+var noopReducer = (state = emptyObject) => state;
+function combineSlices(...slices) {
+  const reducerMap = Object.fromEntries(getReducers(slices));
+  const getReducer = () => Object.keys(reducerMap).length ? combineReducers2(reducerMap) : noopReducer;
+  let reducer = getReducer();
+  function combinedReducer(state, action) {
+    return reducer(state, action);
+  }
+  combinedReducer.withLazyLoadedSlices = () => combinedReducer;
+  const initialStateCache = {};
+  const inject = (slice, config = {}) => {
+    const {
+      reducerPath,
+      reducer: reducerToInject
+    } = slice;
+    const currentReducer = reducerMap[reducerPath];
+    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
+      if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+        console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
+      }
+      return combinedReducer;
+    }
+    if (config.overrideExisting && currentReducer !== reducerToInject) {
+      delete initialStateCache[reducerPath];
+    }
+    reducerMap[reducerPath] = reducerToInject;
+    reducer = getReducer();
+    return combinedReducer;
+  };
+  const selector = Object.assign(function makeSelector(selectorFn, selectState) {
+    return function selector2(state, ...args) {
+      return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap, initialStateCache), ...args);
+    };
+  }, {
+    original
+  });
+  return Object.assign(combinedReducer, {
+    inject,
+    selector
+  });
+}
+
+// src/formatProdErrorMessage.ts
+function formatProdErrorMessage(code) {
+  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
+}
+export {
+  ReducerType,
+  SHOULD_AUTOBATCH,
+  TaskAbortError,
+  Tuple,
+  addListener,
+  asyncThunkCreator,
+  autoBatchEnhancer,
+  buildCreateSlice,
+  clearAllListeners,
+  combineSlices,
+  configureStore,
+  createAction,
+  createActionCreatorInvariantMiddleware,
+  createAsyncThunk,
+  createDraftSafeSelector,
+  createDraftSafeSelectorCreator,
+  createDynamicMiddleware,
+  createEntityAdapter,
+  createImmutableStateInvariantMiddleware,
+  createListenerMiddleware,
+  produce as createNextState,
+  createReducer,
+  createSelector,
+  createSelectorCreator,
+  createSerializableStateInvariantMiddleware,
+  createSlice,
+  current,
+  findNonSerializableValue,
+  formatProdErrorMessage,
+  freeze,
+  isActionCreator,
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isDraft,
+  isFSA as isFluxStandardAction,
+  isFulfilled,
+  isImmutableDefault,
+  isPending,
+  isPlain,
+  isRejected,
+  isRejectedWithValue,
+  lruMemoize,
+  miniSerializeError,
+  nanoid,
+  original2 as original,
+  prepareAutoBatched,
+  removeListener,
+  unwrapResult,
+  weakMapMemoize
+};
+//# sourceMappingURL=redux-toolkit.legacy-esm.js.map
Index: node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../src/index.ts","../src/immerImports.ts","../src/reselectImports.ts","../src/createDraftSafeSelector.ts","../src/reduxImports.ts","../src/devtoolsExtension.ts","../src/getDefaultMiddleware.ts","../src/tsHelpers.ts","../src/createAction.ts","../src/actionCreatorInvariantMiddleware.ts","../src/utils.ts","../src/immutableStateInvariantMiddleware.ts","../src/serializableStateInvariantMiddleware.ts","../src/autoBatchEnhancer.ts","../src/getDefaultEnhancers.ts","../src/configureStore.ts","../src/mapBuilders.ts","../src/createReducer.ts","../src/matchers.ts","../src/nanoid.ts","../src/createAsyncThunk.ts","../src/createSlice.ts","../src/entities/entity_state.ts","../src/entities/state_selectors.ts","../src/entities/state_adapter.ts","../src/entities/utils.ts","../src/entities/unsorted_state_adapter.ts","../src/entities/sorted_state_adapter.ts","../src/entities/create_adapter.ts","../src/listenerMiddleware/exceptions.ts","../src/listenerMiddleware/utils.ts","../src/listenerMiddleware/task.ts","../src/listenerMiddleware/index.ts","../src/dynamicMiddleware/index.ts","../src/combineSlices.ts","../src/formatProdErrorMessage.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage';\nexport * from 'redux';\nexport { freeze, original } from 'immer';\nexport { createNextState, current, isDraft } from './immerImports';\nexport type { Draft, WritableDraft } from 'immer';\nexport { createSelector, lruMemoize } from 'reselect';\nexport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport type { Selector, OutputSelector } from 'reselect';\nexport { createDraftSafeSelector, createDraftSafeSelectorCreator } from './createDraftSafeSelector';\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';\nexport {\n// js\nconfigureStore } from './configureStore';\nexport type {\n// types\nConfigureStoreOptions, EnhancedStore } from './configureStore';\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension';\nexport {\n// js\ncreateAction, isActionCreator, isFSA as isFluxStandardAction } from './createAction';\nexport type {\n// types\nPayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction } from './createAction';\nexport {\n// js\ncreateReducer } from './createReducer';\nexport type {\n// types\nActions, CaseReducer, CaseReducers } from './createReducer';\nexport {\n// js\ncreateSlice, buildCreateSlice, asyncThunkCreator, ReducerType } from './createSlice';\nexport type {\n// types\nCreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, ReducerCreators, SliceSelectors } from './createSlice';\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nexport {\n// js\ncreateImmutableStateInvariantMiddleware, isImmutableDefault } from './immutableStateInvariantMiddleware';\nexport type {\n// types\nImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\nexport {\n// js\ncreateSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nSerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nActionReducerMapBuilder, AsyncThunkReducers } from './mapBuilders';\nexport { Tuple } from './utils';\nexport { createEntityAdapter } from './entities/create_adapter';\nexport type { EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer } from './entities/models';\nexport { createAsyncThunk, unwrapResult, miniSerializeError } from './createAsyncThunk';\nexport type { AsyncThunk, AsyncThunkConfig, AsyncThunkDispatchConfig, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, GetState, GetThunkAPI, SerializedError, CreateAsyncThunkFunction } from './createAsyncThunk';\nexport {\n// js\nisAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue } from './matchers';\nexport type {\n// types\nActionMatchingAllOf, ActionMatchingAnyOf } from './matchers';\nexport { nanoid } from './nanoid';\nexport type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult } from './listenerMiddleware/index';\nexport type { AnyListenerPredicate } from './listenerMiddleware/types';\nexport { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError } from './listenerMiddleware/index';\nexport type { AddMiddleware, DynamicDispatch, DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './dynamicMiddleware/types';\nexport { createDynamicMiddleware } from './dynamicMiddleware/index';\nexport { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer } from './autoBatchEnhancer';\nexport type { AutoBatchOptions } from './autoBatchEnhancer';\nexport { combineSlices } from './combineSlices';\nexport type { CombinedSliceReducer, WithSlice, WithSlicePreloadedState } from './combineSlices';\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers';\nexport { formatProdErrorMessage } from './formatProdErrorMessage';","export { current, isDraft, produce as createNextState, isDraftable, setUseStrictIteration } from 'immer';","export { createSelectorCreator, weakMapMemoize } from 'reselect';","import { current, isDraft } from './immerImports';\nimport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (...args: unknown[]) => {\n  const createSelector = (createSelectorCreator as any)(...args);\n  const createDraftSafeSelector = Object.assign((...args: unknown[]) => {\n    const selector = createSelector(...args);\n    const wrappedSelector = (value: unknown, ...rest: unknown[]) => selector(isDraft(value) ? current(value) : value, ...rest);\n    Object.assign(wrappedSelector, selector);\n    return wrappedSelector as any;\n  }, {\n    withTypes: () => createDraftSafeSelector\n  });\n  return createDraftSafeSelector;\n};\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector = /* @__PURE__ */\ncreateDraftSafeSelectorCreator(weakMapMemoize);","export { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from 'redux';","import type { Action, ActionCreator, StoreEnhancer } from 'redux';\nimport { compose } from './reduxImports';\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string;\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | {\n    [key: string]: ActionCreator<any>;\n  };\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number;\n  /**\n   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\n   *\n   * @default 50\n   */\n  maxAge?: number;\n  /**\n   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?: boolean | {\n    /**\n     * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n     * - `false` - will handle also circular references.\n     * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n     * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n     *   For each of them you can indicate if to include (by setting as `true`).\n     *   For `function` key you can also specify a custom function which handles serialization.\n     *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n     */\n    options?: undefined | boolean | {\n      date?: true;\n      regex?: true;\n      undefined?: true;\n      error?: true;\n      symbol?: true;\n      map?: true;\n      set?: true;\n      function?: true | ((fn: (...args: any[]) => any) => string);\n    };\n    /**\n     * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\n     * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n     * key. So you can deserialize it back while importing or persisting data.\n     * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\n     */\n    replacer?: (key: string, value: unknown) => any;\n    /**\n     * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n     * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n     * as an example on how to serialize special data types and get them back.\n     */\n    reviver?: (key: string, value: unknown) => any;\n    /**\n     * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n     * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n     * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n     */\n    immutable?: any;\n    /**\n     * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n     */\n    refs?: any;\n  };\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A;\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S;\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[];\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[];\n  /**\n   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean;\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean;\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string;\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean;\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean;\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean;\n  /**\n   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean;\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean;\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean;\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean;\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom';\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom';\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean;\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean;\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean;\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean;\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean;\n  };\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string);\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number;\n}\ntype Compose = typeof compose;\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose;\n  <StoreExt extends {}>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\n  if (arguments.length === 0) return undefined;\n  if (typeof arguments[0] === 'object') return compose;\n  return compose.apply(null, arguments as any as Function[]);\n};\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>;\n} = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION__ : function () {\n  return function (noop) {\n    return noop;\n  };\n};","import type { Middleware, UnknownAction } from 'redux';\nimport type { ThunkMiddleware } from 'redux-thunk';\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk';\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware';\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware';\nimport type { ExcludeFromTuple } from './tsHelpers';\nimport { Tuple } from './utils';\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean';\n}\ninterface ThunkOptions<E = any> {\n  extraArgument: E;\n}\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions;\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;\n}\nexport type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {\n  thunk: false;\n} ? never : O extends {\n  thunk: {\n    extraArgument: infer E;\n  };\n} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;\nexport type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {\n  thunk: true;\n  immutableCheck: true;\n  serializableCheck: true;\n  actionCreatorCheck: true;\n}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;\nexport const buildGetDefaultMiddleware = <S = any,>(): GetDefaultMiddleware<S> => function getDefaultMiddleware(options) {\n  const {\n    thunk = true,\n    immutableCheck = true,\n    serializableCheck = true,\n    actionCreatorCheck = true\n  } = options ?? {};\n  let middlewareArray = new Tuple<Middleware[]>();\n  if (thunk) {\n    if (isBoolean(thunk)) {\n      middlewareArray.push(thunkMiddleware);\n    } else {\n      middlewareArray.push(withExtraArgument(thunk.extraArgument));\n    }\n  }\n  if (process.env.NODE_ENV !== 'production') {\n    if (immutableCheck) {\n      /* PROD_START_REMOVE_UMD */\n      let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(immutableCheck)) {\n        immutableOptions = immutableCheck;\n      }\n      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n      /* PROD_STOP_REMOVE_UMD */\n    }\n    if (serializableCheck) {\n      let serializableOptions: SerializableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(serializableCheck)) {\n        serializableOptions = serializableCheck;\n      }\n      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n    }\n    if (actionCreatorCheck) {\n      let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {};\n      if (!isBoolean(actionCreatorCheck)) {\n        actionCreatorOptions = actionCreatorCheck;\n      }\n      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n    }\n  }\n  return middlewareArray as any;\n};","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport { isAction } from './reduxImports';\nimport type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<P = void, T extends string = string, M = never, E = never> = {\n  payload: P;\n  type: T;\n} & ([M] extends [never] ? {} : {\n  meta: M;\n}) & ([E] extends [never] ? {} : {\n  error: E;\n});\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> = ((...args: any[]) => {\n  payload: P;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  error: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n  error: any;\n});\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {\n  error: infer E;\n} ? E : never, ReturnType<PA> extends {\n  meta: infer M;\n} ? M : never> : void;\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T;\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>;\n};\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>;\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>;\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>;\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>,\n// else\nIsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>,\n// else\nIfVoid<P, ActionCreatorWithoutPayload<T>,\n// else\nIfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>,\n// else\nActionCreatorWithPayload<P, T>>>>>>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args);\n      if (!prepared) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(0) : 'prepareAction did not return an object');\n      }\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && {\n          meta: prepared.meta\n        }),\n        ...('error' in prepared && {\n          error: prepared.error\n        })\n      };\n    }\n    return {\n      type,\n      payload: args[0]\n    };\n  }\n  actionCreator.toString = () => `${type}`;\n  actionCreator.type = type;\n  actionCreator.match = (action: unknown): action is PayloadAction => isAction(action) && action.type === type;\n  return actionCreator;\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function {\n  return typeof action === 'function' && 'type' in action &&\n  // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n  hasMatchFunction(action as any);\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string;\n  payload?: unknown;\n  error?: unknown;\n  meta?: unknown;\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1;\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends ((...args: any[]) => any) ? True : False;","import type { Middleware } from 'redux';\nimport { isActionCreator as isRTKAction } from './createAction';\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & {\n    type?: unknown;\n  };\n}\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : [];\n  const actionName = splitType[splitType.length - 1] || 'actionCreator';\n  return `Detected an action creator with type \"${type || 'unknown'}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nexport function createActionCreatorInvariantMiddleware(options: ActionCreatorInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  }\n  const {\n    isActionCreator = isRTKAction\n  } = options;\n  return () => next => action => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type));\n    }\n    return next(action);\n  };\n}","import { createNextState, isDraftable } from './immerImports';\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0;\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now();\n      try {\n        return fn();\n      } finally {\n        const finished = Date.now();\n        elapsed += finished - started;\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n      }\n    }\n  };\n}\nexport function delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {\n  constructor(length: number);\n  constructor(...items: Items);\n  constructor(...items: any[]) {\n    super(...items);\n    Object.setPrototypeOf(this, Tuple.prototype);\n  }\n  static override get [Symbol.species]() {\n    return Tuple as any;\n  }\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr);\n  }\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this));\n    }\n    return new Tuple(...arr.concat(this));\n  }\n}\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val;\n}\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | PromiseLike<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve: any;\n  let reject: any;\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve,\n    reject\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Middleware } from 'redux';\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware';\nimport { getTimeMeasureUtils } from './utils';\ntype EntryProcessor = (key: string, value: any) => any;\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value);\n}\nexport function trackForMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths | undefined, obj: any) {\n  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);\n    }\n  };\n}\ninterface TrackedProperty {\n  value: any;\n  children: Record<string, any>;\n}\nfunction trackProperties(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], obj: Record<string, any>, path: string = '', checkedObjects: Set<Record<string, any>> = new Set()) {\n  const tracked: Partial<TrackedProperty> = {\n    value: obj\n  };\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj);\n    tracked.children = {};\n    const hasIgnoredPaths = ignoredPaths.length > 0;\n    for (const key in obj) {\n      const nestedPath = path ? path + '.' + key : key;\n      if (hasIgnoredPaths) {\n        const hasMatches = ignoredPaths.some(ignored => {\n          if (ignored instanceof RegExp) {\n            return ignored.test(nestedPath);\n          }\n          return nestedPath === ignored;\n        });\n        if (hasMatches) {\n          continue;\n        }\n      }\n      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);\n    }\n  }\n  return tracked as TrackedProperty;\n}\nfunction detectMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, path: string = ''): {\n  wasMutated: boolean;\n  path?: string;\n} {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined;\n  const sameRef = prevObj === obj;\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return {\n      wasMutated: true,\n      path\n    };\n  }\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return {\n      wasMutated: false\n    };\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {};\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true;\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true;\n  }\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n    if (result.wasMutated) {\n      return result;\n    }\n  }\n  return {\n    wasMutated: false\n  };\n}\ntype IsImmutableFunc = (value: any) => boolean;\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc;\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths;\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number;\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(options: ImmutableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    function stringify(obj: any, serializer?: EntryProcessor, indent?: string | number, decycler?: EntryProcessor): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\n    }\n    function getSerialize(serializer?: EntryProcessor, decycler?: EntryProcessor): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = [];\n      if (!decycler) decycler = function (_: string, value: any) {\n        if (stack[0] === value) return '[Circular ~]';\n        return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n      };\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this);\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value);\n        } else stack.push(value);\n        return serializer == null ? value : serializer.call(this, key, value);\n      };\n    }\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32\n    } = options;\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n    return ({\n      getState\n    }) => {\n      let state = getState();\n      let tracker = track(state);\n      let result;\n      return next => action => {\n        const measureUtils = getTimeMeasureUtils(warnAfter, 'ImmutableStateInvariantMiddleware');\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ''}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        const dispatchedAction = next(action);\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ''}. Take a look at the reducer(s) handling the action ${stringify(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n        return dispatchedAction;\n      };\n    };\n  }\n}","import type { Middleware } from 'redux';\nimport { isAction, isPlainObject } from './reduxImports';\nimport { getTimeMeasureUtils } from './utils';\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val;\n  return val == null || type === 'string' || type === 'boolean' || type === 'number' || Array.isArray(val) || isPlainObject(val);\n}\ninterface NonSerializableValue {\n  keyPath: string;\n  value: unknown;\n}\nexport type IgnorePaths = readonly (string | RegExp)[];\n\n/**\n * @public\n */\nexport function findNonSerializableValue(value: unknown, path: string = '', isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], cache?: WeakSet<object>): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false;\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value\n    };\n  }\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  if (cache?.has(value)) return false;\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue\n      };\n    }\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n      if (foundNestedSerializable) {\n        return foundNestedSerializable;\n      }\n    }\n  }\n  if (cache && isNestedFrozen(value)) cache.add(value);\n  return false;\n}\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false;\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue;\n    if (!isNestedFrozen(nestedValue)) return false;\n  }\n  return true;\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean;\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][];\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[];\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number;\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean;\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean;\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean;\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(options: SerializableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false\n    } = options;\n    const cache: WeakSet<object> | undefined = !disableCache && WeakSet ? new WeakSet() : undefined;\n    return storeAPI => next => action => {\n      if (!isAction(action)) {\n        return next(action);\n      }\n      const result = next(action);\n      const measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type as any) !== -1)) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(action, '', isSerializable, getEntries, ignoredActionPaths, cache);\n          if (foundActionNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundActionNonSerializableValue;\n            console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, '\\nTake a look at the logic that dispatched this action: ', action, '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)');\n          }\n        });\n      }\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState();\n          const foundStateNonSerializableValue = findNonSerializableValue(state, '', isSerializable, getEntries, ignoredPaths, cache);\n          if (foundStateNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundStateNonSerializableValue;\n            console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n      }\n      return result;\n    };\n  }\n}","import type { StoreEnhancer } from 'redux';\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch';\nexport const prepareAutoBatched = <T,>() => (payload: T): {\n  payload: T;\n  meta: unknown;\n} => ({\n  payload,\n  meta: {\n    [SHOULD_AUTOBATCH]: true\n  }\n});\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout);\n  };\n};\nexport type AutoBatchOptions = {\n  type: 'tick';\n} | {\n  type: 'timer';\n  timeout: number;\n} | {\n  type: 'raf';\n} | {\n  type: 'callback';\n  queueNotification: (notify: () => void) => void;\n};\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer = (options: AutoBatchOptions = {\n  type: 'raf'\n}): StoreEnhancer => next => (...args) => {\n  const store = next(...args);\n  let notifying = true;\n  let shouldNotifyAtEndOfTick = false;\n  let notificationQueued = false;\n  const listeners = new Set<() => void>();\n  const queueCallback = options.type === 'tick' ? queueMicrotask : options.type === 'raf' ?\n  // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n  typeof window !== 'undefined' && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === 'callback' ? options.queueNotification : createQueueWithTimer(options.timeout);\n  const notifyListeners = () => {\n    // We're running at the end of the event loop tick.\n    // Run the real listener callbacks to actually update the UI.\n    notificationQueued = false;\n    if (shouldNotifyAtEndOfTick) {\n      shouldNotifyAtEndOfTick = false;\n      listeners.forEach(l => l());\n    }\n  };\n  return Object.assign({}, store, {\n    // Override the base `store.subscribe` method to keep original listeners\n    // from running if we're delaying notifications\n    subscribe(listener: () => void) {\n      // Each wrapped listener will only call the real listener if\n      // the `notifying` flag is currently active when it's called.\n      // This lets the base store work as normal, while the actual UI\n      // update becomes controlled by this enhancer.\n      const wrappedListener: typeof listener = () => notifying && listener();\n      const unsubscribe = store.subscribe(wrappedListener);\n      listeners.add(listener);\n      return () => {\n        unsubscribe();\n        listeners.delete(listener);\n      };\n    },\n    // Override the base `store.dispatch` method so that we can check actions\n    // for the `shouldAutoBatch` flag and determine if batching is active\n    dispatch(action: any) {\n      try {\n        // If the action does _not_ have the `shouldAutoBatch` flag,\n        // we resume/continue normal notify-after-each-dispatch behavior\n        notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n        // If a `notifyListeners` microtask was queued, you can't cancel it.\n        // Instead, we set a flag so that it's a no-op when it does run\n        shouldNotifyAtEndOfTick = !notifying;\n        if (shouldNotifyAtEndOfTick) {\n          // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n          // a microtask to notify listeners at the end of the event loop tick.\n          // Make sure we only enqueue this _once_ per tick.\n          if (!notificationQueued) {\n            notificationQueued = true;\n            queueCallback(notifyListeners);\n          }\n        }\n        // Go ahead and process the action as usual, including reducers.\n        // If normal notification behavior is enabled, the store will notify\n        // all of its own listeners, and the wrapper callbacks above will\n        // see `notifying` is true and pass on to the real listener callbacks.\n        // If we're \"batching\" behavior, then the wrapped callbacks will\n        // bail out, causing the base store notification behavior to be no-ops.\n        return store.dispatch(action);\n      } finally {\n        // Assume we're back to normal behavior after each action\n        notifying = true;\n      }\n    }\n  });\n};","import type { StoreEnhancer } from 'redux';\nimport type { AutoBatchOptions } from './autoBatchEnhancer';\nimport { autoBatchEnhancer } from './autoBatchEnhancer';\nimport { Tuple } from './utils';\nimport type { Middlewares } from './configureStore';\nimport type { ExtractDispatchExtensions } from './tsHelpers';\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions;\n};\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>]>;\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>,>(middlewareEnhancer: StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>): GetDefaultEnhancers<M> => function getDefaultEnhancers(options) {\n  const {\n    autoBatch = true\n  } = options ?? {};\n  let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer);\n  if (autoBatch) {\n    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined));\n  }\n  return enhancerArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Reducer, ReducersMapObject, Middleware, Action, StoreEnhancer, Store, UnknownAction } from 'redux';\nimport { applyMiddleware, createStore, compose, combineReducers, isPlainObject } from './reduxImports';\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';\nimport { composeWithDevTools } from './devtoolsExtension';\nimport type { ThunkMiddlewareFor, GetDefaultMiddleware } from './getDefaultMiddleware';\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware';\nimport type { ExtractDispatchExtensions, ExtractStoreExtensions, ExtractStateExtensions, UnknownIfNonSpecific } from './tsHelpers';\nimport type { Tuple } from './utils';\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers';\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers';\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions;\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean;\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P;\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;\n}\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;\ntype Enhancers = ReadonlyArray<StoreEnhancer>;\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>, StoreEnhancer]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>();\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined\n  } = options || {};\n  let rootReducer: Reducer<S, A, P>;\n  if (typeof reducer === 'function') {\n    rootReducer = reducer;\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>;\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(1) : '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\n  }\n  if (process.env.NODE_ENV !== 'production' && middleware && typeof middleware !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(2) : '`middleware` field must be a callback');\n  }\n  let finalMiddleware: Tuple<Middlewares<S>>;\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware);\n    if (process.env.NODE_ENV !== 'production' && !Array.isArray(finalMiddleware)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(3) : 'when using a middleware builder function, an array of middleware must be returned');\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware();\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(4) : 'each middleware provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>();\n    finalMiddleware.forEach(middleware => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(42) : 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.');\n      }\n      middlewareReferences.add(middleware);\n    });\n  }\n  let finalCompose = compose;\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools)\n    });\n  }\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer);\n  if (process.env.NODE_ENV !== 'production' && enhancers && typeof enhancers !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(5) : '`enhancers` field must be a callback');\n  }\n  let storeEnhancers = typeof enhancers === 'function' ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(6) : '`enhancers` callback must return an array');\n  }\n  if (process.env.NODE_ENV !== 'production' && storeEnhancers.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(7) : 'each enhancer provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n    console.error('middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`');\n  }\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers);\n  return createStore(rootReducer, preloadedState as P, composedEnhancer);\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7 } from \"@reduxjs/toolkit\";\nimport type { Action } from 'redux';\nimport type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';\nimport type { TypeGuard } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk';\nexport type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;\n  rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;\n  fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;\n  settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;\n};\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>;\n  type: Type;\n};\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;\n\n  /**\n   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.\n   * @remarks\n   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param asyncThunk - The async thunk action creator itself.\n   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.\n   * @example\n  ```ts no-transpile\n  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'\n  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {\n  const response = await fetch(`https://reqres.in/api/users/${id}`)\n  return (await response.json()).data\n  })\n  const reducer = createReducer(initialState, (builder) => {\n  builder.addAsyncThunk(fetchUserById, {\n    pending: (state, action) => {\n      state.fetchUserById.loading = 'pending'\n    },\n    fulfilled: (state, action) => {\n      state.fetchUserById.data = action.payload\n    },\n    rejected: (state, action) => {\n      state.fetchUserById.error = action.error\n    },\n    settled: (state, action) => {\n      state.fetchUserById.loading = action.meta.requestStatus\n    },\n  })\n  })\n   */\n  addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n  ```ts\n  import {\n  createAction,\n  createReducer,\n  AsyncThunk,\n  UnknownAction,\n  } from \"@reduxjs/toolkit\";\n  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n  type PendingAction = ReturnType<GenericAsyncThunk[\"pending\"]>;\n  type RejectedAction = ReturnType<GenericAsyncThunk[\"rejected\"]>;\n  type FulfilledAction = ReturnType<GenericAsyncThunk[\"fulfilled\"]>;\n  const initialState: Record<string, string> = {};\n  const resetAction = createAction(\"reset-tracked-loading-state\");\n  function isPendingAction(action: UnknownAction): action is PendingAction {\n  return typeof action.type === \"string\" && action.type.endsWith(\"/pending\");\n  }\n  const reducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(resetAction, () => initialState)\n    // matcher can be defined outside as a type predicate function\n    .addMatcher(isPendingAction, (state, action) => {\n      state[action.meta.requestId] = \"pending\";\n    })\n    .addMatcher(\n      // matcher can be defined inline as a type predicate function\n      (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"rejected\";\n      }\n    )\n    // matcher can just return boolean and the matcher can receive a generic argument\n    .addMatcher<FulfilledAction>(\n      (action) => action.type.endsWith(\"/fulfilled\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"fulfilled\";\n      }\n    );\n  });\n  ```\n   */\n  addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n  ```ts\n  import { createReducer } from '@reduxjs/toolkit'\n  const initialState = { otherActions: 0 }\n  const reducer = createReducer(initialState, builder => {\n  builder\n    // .addCase(...)\n    // .addMatcher(...)\n    .addDefaultCase((state, action) => {\n      state.otherActions++\n    })\n  })\n  ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {};\n}\nexport function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [CaseReducers<S, any>, ActionMatcherDescriptionCollection<S>, CaseReducer<S, Action> | undefined] {\n  const actionsMap: CaseReducers<S, any> = {};\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = [];\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined;\n  const builder = {\n    addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<S>) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(26) : '`builder.addCase` should only be called before calling `builder.addMatcher`');\n        }\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(27) : '`builder.addCase` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n      if (!type) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(28) : '`builder.addCase` cannot be called with an empty action type');\n      }\n      if (type in actionsMap) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(29) : '`builder.addCase` cannot be called with two reducers for the same action type ' + `'${type}'`);\n      }\n      actionsMap[type] = reducer;\n      return builder;\n    },\n    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>) {\n      if (process.env.NODE_ENV !== 'production') {\n        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(43) : '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;\n      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;\n      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;\n      if (reducers.settled) actionMatchers.push({\n        matcher: asyncThunk.settled,\n        reducer: reducers.settled\n      });\n      return builder;\n    },\n    addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<S, A extends Action ? A : A & Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(30) : '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      actionMatchers.push({\n        matcher,\n        reducer\n      });\n      return builder;\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(31) : '`builder.addDefaultCase` can only be called once');\n        }\n      }\n      defaultCaseReducer = reducer;\n      return builder;\n    }\n  };\n  builderCallback(builder);\n  return [actionsMap, actionMatchers, defaultCaseReducer];\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Draft } from 'immer';\nimport { createNextState, isDraft, isDraftable, setUseStrictIteration } from './immerImports';\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { ActionReducerMapBuilder } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { NoInfer, TypeGuard } from './tsHelpers';\nimport { freezeDraftable } from './utils';\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>;\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>;\n  reducer: CaseReducer<S, NoInfer<A>>;\n};\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;\nexport type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void };\nexport type NotFunction<T> = T extends Function ? never : T;\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function';\n}\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S;\n};\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n```ts\nimport {\n  createAction,\n  createReducer,\n  UnknownAction,\n  PayloadAction,\n} from \"@reduxjs/toolkit\";\n\nconst increment = createAction<number>(\"increment\");\nconst decrement = createAction<number>(\"decrement\");\n\nfunction isActionWithNumberPayload(\n  action: UnknownAction\n): action is PayloadAction<number> {\n  return typeof action.payload === \"number\";\n}\n\nconst reducer = createReducer(\n  {\n    counter: 0,\n    sumOfNumberPayloads: 0,\n    unhandledActions: 0,\n  },\n  (builder) => {\n    builder\n      .addCase(increment, (state, action) => {\n        // action is inferred correctly here\n        state.counter += action.payload;\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {\n        state.counter -= action.payload;\n      })\n      // You can apply a \"matcher function\" to incoming actions\n      .addMatcher(isActionWithNumberPayload, (state, action) => {})\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {});\n  }\n);\n```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n    }\n  }\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S;\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState());\n  } else {\n    const frozenInitialState = freezeDraftable(initialState);\n    getInitialState = () => frozenInitialState;\n  }\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n      matcher\n    }) => matcher(action)).map(({\n      reducer\n    }) => reducer)];\n    if (caseReducers.filter(cr => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer];\n    }\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S>; // We can assume this is already a draft\n          const result = caseReducer(draft, action);\n          if (result === undefined) {\n            return previousState;\n          }\n          return result as S;\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action);\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState;\n            }\n            throw Error('A case reducer on a non-draftable value must not return undefined');\n          }\n          return result as S;\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action);\n          });\n        }\n      }\n      return previousState;\n    }, state);\n  }\n  reducer.getInitialState = getInitialState;\n  return reducer as ReducerWithInitialState<S>;\n}","import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action);\n  } else {\n    return matcher(action);\n  }\n};\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]) {\n  if (!action || !action.meta) return false;\n  const hasValidRequestId = typeof action.meta.requestId === 'string';\n  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n  return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return typeof a[0] === 'function' && 'pending' in a[0] && 'fulfilled' in a[0] && 'rejected' in a[0];\n}\nexport type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction;\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.pending));\n}\nexport type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.rejected));\n}\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {\n  rejectValue: infer RejectedValue;\n}> ? {\n  payload: RejectedValue;\n} : unknown);\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue;\n  };\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0]);\n  }\n  return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.fulfilled));\n}\nexport type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;\nexport type AnyAsyncThunk = {\n  pending: {\n    match: (action: any) => action is any;\n  };\n  fulfilled: {\n    match: (action: any) => action is any;\n  };\n  rejected: {\n    match: (action: any) => action is any;\n  };\n};\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}","// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\n/**\n *\n * @public\n */\nexport let nanoid = (size = 21) => {\n  let id = '';\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size;\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[Math.random() * 64 | 0];\n  }\n  return id;\n};","import type { Dispatch, UnknownAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport type { ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport { isAnyOf } from './matchers';\nimport { nanoid } from './nanoid';\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown, SafePromise } from './tsHelpers';\nexport type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {\n  dispatch: D;\n  getState: () => S;\n  extra: E;\n  requestId: string;\n  signal: AbortSignal;\n  abort: (reason?: string) => void;\n  rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;\n  fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;\n};\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string;\n  message?: string;\n  stack?: string;\n  code?: string;\n}\nconst commonProperties: Array<keyof SerializedError> = ['name', 'message', 'stack', 'code'];\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue';\n  constructor(public readonly payload: Payload, public readonly meta: RejectedMeta) {}\n}\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta';\n  constructor(public readonly payload: Payload, public readonly meta: FulfilledMeta) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {};\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property];\n      }\n    }\n    return simpleError;\n  }\n  return {\n    message: String(value)\n  };\n};\nexport type AsyncThunkConfig = {\n  state?: unknown;\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;\n  extra?: unknown;\n  rejectValue?: unknown;\n  serializedErrorType?: unknown;\n  pendingMeta?: unknown;\n  fulfilledMeta?: unknown;\n  rejectedMeta?: unknown;\n};\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State;\n} ? State : unknown;\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends {\n  extra: infer Extra;\n} ? Extra : unknown;\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch;\n} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue;\n} ? RejectValue : unknown;\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta;\n} ? PendingMeta : unknown;\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta;\n} ? FulfilledMeta : unknown;\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta;\n} ? RejectedMeta : unknown;\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType;\n} ? GetSerializedErrorType : SerializedError;\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {\n  abort: (reason?: string) => void;\n  requestId: string;\n  arg: ThunkArg;\n  unwrap: () => Promise<Returned>;\n};\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal;\n}\ntype AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg,\n// any handling\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// unknown handling\nunknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n: [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n: [void] extends [ThunkArg] // make optional\n? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n: [undefined] extends [ThunkArg] ? WithStrictNullChecks<\n// with strict nullChecks: make optional\n(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// without strict null checks this will match everything, so don't make it optional\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> // default case: normal argument\n: (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean;\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string;\n} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   *\n   * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n   * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n   */\n  getPendingMeta?(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   */\n  getPendingMeta(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}>;\nexport type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?], undefined, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'pending';\n} & GetPendingMeta<ThunkApiConfig>>;\nexport type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Error | null, string, ThunkArg, GetRejectValue<ThunkApiConfig>?, GetRejectedMeta<ThunkApiConfig>?], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'rejected';\n  aborted: boolean;\n  condition: boolean;\n} & (({\n  rejectedWithValue: false;\n} & { [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined }) | ({\n  rejectedWithValue: true;\n} & GetRejectedMeta<ThunkApiConfig>))>;\nexport type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?], Returned, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'fulfilled';\n} & GetFulfilledMeta<ThunkApiConfig>>;\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;\n  fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;\n  // matchSettled?\n  settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;\n  typePrefix: string;\n};\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;\nexport type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n  withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\nconst externalAbortMessage = 'External signal was aborted';\nexport const createAsyncThunk = /* @__PURE__ */(() => {\n  function createAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>;\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>;\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>;\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>;\n    const fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/fulfilled', (payload: Returned, requestId: string, arg: ThunkArg, meta?: FulfilledMeta) => ({\n      payload,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'fulfilled' as const\n      }\n    }));\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/pending', (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n      payload: undefined,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'pending' as const\n      }\n    }));\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/rejected', (error: Error | null, requestId: string, arg: ThunkArg, payload?: RejectedValue, meta?: RejectedMeta) => ({\n      payload,\n      error: (options && options.serializeError || miniSerializeError)(error || 'Rejected') as GetSerializedErrorType<ThunkApiConfig>,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        rejectedWithValue: !!payload,\n        requestStatus: 'rejected' as const,\n        aborted: error?.name === 'AbortError',\n        condition: error?.name === 'ConditionError'\n      }\n    }));\n    function actionCreator(arg: ThunkArg, {\n      signal\n    }: AsyncThunkDispatchConfig = {}): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n        const abortController = new AbortController();\n        let abortHandler: (() => void) | undefined;\n        let abortReason: string | undefined;\n        function abort(reason?: string) {\n          abortReason = reason;\n          abortController.abort();\n        }\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage);\n          } else {\n            signal.addEventListener('abort', () => abort(externalAbortMessage), {\n              once: true\n            });\n          }\n        }\n        const promise = async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>;\n          try {\n            let conditionResult = options?.condition?.(arg, {\n              getState,\n              extra\n            });\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult;\n            }\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.'\n              };\n            }\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted'\n                });\n              };\n              abortController.signal.addEventListener('abort', abortHandler, {\n                once: true\n              });\n            });\n            dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n              requestId,\n              arg\n            }, {\n              getState,\n              extra\n            })) as any);\n            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n              dispatch,\n              getState,\n              extra,\n              requestId,\n              signal: abortController.signal,\n              abort,\n              rejectWithValue: ((value: RejectedValue, meta?: RejectedMeta) => {\n                return new RejectWithValue(value, meta);\n              }) as any,\n              fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                return new FulfillWithMeta(value, meta);\n              }) as any\n            })).then(result => {\n              if (result instanceof RejectWithValue) {\n                throw result;\n              }\n              if (result instanceof FulfillWithMeta) {\n                return fulfilled(result.payload, requestId, arg, result.meta);\n              }\n              return fulfilled(result as any, requestId, arg);\n            })]);\n          } catch (err) {\n            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err as any, requestId, arg);\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler);\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && (finalAction as any).meta.condition;\n          if (!skipDispatch) {\n            dispatch(finalAction as any);\n          }\n          return finalAction;\n        }();\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult);\n          }\n        });\n      };\n    }\n    return Object.assign(actionCreator as AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig>, {\n      pending,\n      rejected,\n      fulfilled,\n      settled: isAnyOf(rejected, fulfilled),\n      typePrefix\n    });\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk;\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>;\n})();\ninterface UnwrappableAction {\n  payload: any;\n  meta?: any;\n  error?: any;\n}\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {\n  error: any;\n}>['payload'];\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload;\n  }\n  if (action.error) {\n    throw action.error;\n  }\n  return action.payload;\n}\ntype WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return value !== null && typeof value === 'object' && typeof value.then === 'function';\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { Selector } from 'reselect';\nimport type { InjectConfig } from './combineSlices';\nimport type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport type { AsyncThunk, AsyncThunkConfig, AsyncThunkOptions, AsyncThunkPayloadCreator, OverrideThunkApiConfigs } from './createAsyncThunk';\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk';\nimport type { ActionMatcherDescriptionCollection, CaseReducer, ReducerWithInitialState } from './createReducer';\nimport { createReducer } from './createReducer';\nimport type { ActionReducerMapBuilder, AsyncThunkReducers, TypedActionCreator } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { Id, TypeGuard } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\nconst asyncThunkSymbol = /* @__PURE__ */Symbol.for('rtk-slice-createasyncthunk');\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk;\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk\n};\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath;\n};\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice name.\n   */\n  name: Name;\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath;\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>;\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>;\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>;\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State;\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>>;\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {\n    inject: (slice: {\n      reducerPath: string;\n      reducer: Reducer;\n    }, config?: InjectConfig) => void;\n  }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State;\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]?: State | undefined }>>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State;\n};\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name;\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath;\n\n  /**\n   * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n   */\n  initialState: State | (() => State);\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n  ```ts\n  import { createAction, createSlice, Action } from '@reduxjs/toolkit'\n  const incrementBy = createAction<number>('incrementBy')\n  const decrement = createAction('decrement')\n  interface RejectedAction extends Action {\n  error: Error\n  }\n  function isRejectedAction(action: Action): action is RejectedAction {\n  return action.type.endsWith('rejected')\n  }\n  createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {},\n  extraReducers: builder => {\n    builder\n      .addCase(incrementBy, (state, action) => {\n        // action is inferred correctly here if using TS\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {})\n      // You can match a range of action types\n      .addMatcher(\n        isRejectedAction,\n        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n        (state, action) => {}\n      )\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {})\n    }\n  })\n  ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors;\n}\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T;\n};\nexport type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>;\n  prepare: PrepareAction<Action['payload']>;\n};\nexport interface CaseReducerWithPrepareDefinition<State, Action extends PayloadAction> extends CaseReducerWithPrepare<State, Action>, ReducerDefinition<ReducerType.reducerWithPrepare> {}\ntype AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;\n};\ntype AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;\n};\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = { [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K] };\ninterface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {\n  <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;\n  <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;\n  withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n}\nexport interface ReducerCreators<State> {\n  reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;\n  reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;\n  asyncThunk: AsyncThunkCreator<State>;\n  preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare;\n    prepare: Prepare;\n    reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;\n  };\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any;\n};\ntype SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {\n  prepare: any;\n} ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {\n  reducer: any;\n} ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never };\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<CR extends {\n  prepare: any;\n}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ((state: any, action: infer Action) => any) ? Action extends {\n  payload: infer P;\n} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {\n  reducer: infer Reducer;\n} ? Reducer : Definition : never };\ntype RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {\n  unwrapped: S;\n} : never;\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState> };\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends {\n  reducer(s: S, action?: infer A): any;\n} ? {\n  prepare(...a: never[]): Omit<A, 'type'>;\n} : {} };\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`;\n}\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator;\n  };\n}\nexport function buildCreateSlice({\n  creators\n}: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n  return function createSlice<State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {\n    const {\n      name,\n      reducerPath = name as unknown as ReducerPath\n    } = options;\n    if (!name) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(11) : '`name` is a required option for createSlice');\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (options.initialState === undefined) {\n        console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`');\n      }\n    }\n    const reducers = (typeof options.reducers === 'function' ? options.reducers(buildReducerCreators<State>()) : options.reducers) || {};\n    const reducerNames = Object.keys(reducers);\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: []\n    };\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<State>) {\n        const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n        if (!type) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(12) : '`context.addCase` cannot be called with an empty action type');\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(13) : '`context.addCase` cannot be called with two reducers for the same action type: ' + type);\n        }\n        context.sliceCaseReducersByType[type] = reducer;\n        return contextMethods;\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({\n          matcher,\n          reducer\n        });\n        return contextMethods;\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator;\n        return contextMethods;\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer;\n        return contextMethods;\n      }\n    };\n    reducerNames.forEach(reducerName => {\n      const reducerDefinition = reducers[reducerName];\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function'\n      };\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n      } else {\n        handleNormalReducerDefinition<State>(reducerDetails, reducerDefinition as any, contextMethods);\n      }\n    });\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n        }\n      }\n      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = undefined] = typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType\n      };\n      return createReducer(options.initialState, builder => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>);\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer);\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer);\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer);\n        }\n      });\n    }\n    const selectSelf = (state: State) => state;\n    const injectedSelectorCache = new Map<boolean, WeakMap<(rootState: any) => State | undefined, Record<string, (rootState: any) => any>>>();\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>();\n    let _reducer: ReducerWithInitialState<State>;\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer(state, action);\n    }\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer.getInitialState();\n    }\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(reducerPath: CurrentReducerPath, injected = false): Pick<Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'> {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath];\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(15) : 'selectSlice returned undefined for an uninjected slice reducer');\n          }\n        }\n        return sliceState;\n      }\n      function getSelectors(selectState: (rootState: any) => State = selectSelf) {\n        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => new WeakMap());\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {};\n          for (const [name, selector] of Object.entries(options.selectors ?? {})) {\n            map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);\n          }\n          return map;\n        }) as any;\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice);\n        },\n        selectSlice\n      };\n    }\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, {\n        reducerPath: pathOpt,\n        ...config\n      } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath;\n        injectable.inject({\n          reducerPath: newReducerPath,\n          reducer\n        }, config);\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true)\n        } as any;\n      }\n    };\n    return slice;\n  };\n}\nfunction wrapSelector<State, NewState, S extends Selector<State>>(selector: S, selectState: Selector<NewState, State>, getInitialState: () => State, injected?: boolean) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState);\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState();\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(16) : 'selectState returned undefined for an uninjected slice reducer');\n      }\n    }\n    return selector(sliceState, ...args);\n  }\n  wrapper.unwrapped = selector;\n  return wrapper as RemappedSelector<S, NewState>;\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */buildCreateSlice();\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<string, CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>>;\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>;\n  sliceMatchers: ActionMatcherDescriptionCollection<State>;\n  actionCreators: Record<string, Function>;\n}\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ReducerHandlingContextMethods<State>;\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ReducerHandlingContextMethods<State>;\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<State, A extends Action ? A : A & Action>): ReducerHandlingContextMethods<State>;\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * context.exposeAction(\"addPost\", createAction<Post>(\"addPost\"));\n   *\n   * export const { addPost } = slice.actions\n   *\n   * dispatch(addPost(post))\n   */\n  exposeAction(name: string, actionCreator: Function): ReducerHandlingContextMethods<State>;\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * context.exposeCaseReducer(\"addPost\", (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload)\n   * })\n   *\n   * slice.caseReducers.addPost([], addPost(post))\n   */\n  exposeCaseReducer(name: string, reducer: CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>): ReducerHandlingContextMethods<State>;\n}\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string;\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string;\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean;\n}\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(payloadCreator: AsyncThunkPayloadCreator<any, any>, config: AsyncThunkSliceReducerConfig<State, any>): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config\n    };\n  }\n  asyncThunk.withTypes = () => asyncThunk;\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign({\n        // hack so the wrapping function has the same name as the original\n        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n        [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n          return caseReducer(...args);\n        }\n      }[caseReducer.name], {\n        _reducerDefinitionType: ReducerType.reducer\n      } as const);\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer\n      };\n    },\n    asyncThunk: asyncThunk as any\n  };\n}\nfunction handleNormalReducerDefinition<State>({\n  type,\n  reducerName,\n  createNotation\n}: ReducerDetails, maybeReducerWithPrepare: CaseReducer<State, {\n  payload: any;\n  type: string;\n}> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, context: ReducerHandlingContextMethods<State>) {\n  let caseReducer: CaseReducer<State, any>;\n  let prepareCallback: PrepareAction<any> | undefined;\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(17) : 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.');\n    }\n    caseReducer = maybeReducerWithPrepare.reducer;\n    prepareCallback = maybeReducerWithPrepare.prepare;\n  } else {\n    caseReducer = maybeReducerWithPrepare;\n  }\n  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition<State>(reducerDefinition: any): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk;\n}\nfunction isCaseReducerWithPrepareDefinition<State>(reducerDefinition: any): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare;\n}\nfunction handleThunkCaseReducerDefinition<State>({\n  type,\n  reducerName\n}: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, context: ReducerHandlingContextMethods<State>, cAT: typeof _createAsyncThunk | undefined) {\n  if (!cAT) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(18) : 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.');\n  }\n  const {\n    payloadCreator,\n    fulfilled,\n    pending,\n    rejected,\n    settled,\n    options\n  } = reducerDefinition;\n  const thunk = cAT(type, payloadCreator, options as any);\n  context.exposeAction(reducerName, thunk);\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled);\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending);\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected);\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled);\n  }\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop\n  });\n}\nfunction noop() {}","import type { EntityId, EntityState, EntityStateAdapter, EntityStateFactory } from './models';\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<T, Id> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>\n  };\n}\nexport function createInitialStateFactory<T, Id extends EntityId>(stateAdapter: EntityStateAdapter<T, Id>): EntityStateFactory<T, Id> {\n  function getInitialState(state?: undefined, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id>;\n  function getInitialState<S extends object>(additionalState: S, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id> & S;\n  function getInitialState(additionalState: any = {}, entities?: readonly T[] | Record<Id, T>): any {\n    const state = Object.assign(getInitialEntityState(), additionalState);\n    return entities ? stateAdapter.setAll(state, entities) : state;\n  }\n  return {\n    getInitialState\n  };\n}","import type { CreateSelectorFunction, Selector } from 'reselect';\nimport { createDraftSafeSelector } from '../createDraftSafeSelector';\nimport type { EntityId, EntitySelectors, EntityState } from './models';\ntype AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction;\n};\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;\n  function getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;\n  function getSelectors<V>(selectState?: (state: V) => EntityState<T, Id>, options: GetSelectorsOptions = {}): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction\n    } = options;\n    const selectIds = (state: EntityState<T, Id>) => state.ids;\n    const selectEntities = (state: EntityState<T, Id>) => state.entities;\n    const selectAll = createSelector(selectIds, selectEntities, (ids, entities): T[] => ids.map(id => entities[id]!));\n    const selectId = (_: unknown, id: Id) => id;\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id];\n    const selectTotal = createSelector(selectIds, ids => ids.length);\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById)\n      };\n    }\n    const selectGlobalizedEntities = createSelector(selectState as Selector<V, EntityState<T, Id>>, selectEntities);\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(selectGlobalizedEntities, selectId, selectById)\n    };\n  }\n  return {\n    getSelectors\n  };\n}","import { createNextState, isDraft } from '../immerImports';\nimport type { Draft } from 'immer';\nimport type { EntityId, DraftableEntityState, PreventAny } from './models';\nimport type { PayloadAction } from '../createAction';\nimport { isFSA } from '../createAction';\nexport const isDraftTyped = isDraft as <T>(value: T | Draft<T>) => value is Draft<T>;\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(mutator: (state: DraftableEntityState<T, Id>) => void) {\n  const operator = createStateOperator((_: undefined, state: DraftableEntityState<T, Id>) => mutator(state));\n  return function operation<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S {\n    return operator(state as S, undefined);\n  };\n}\nexport function createStateOperator<T, Id extends EntityId, R>(mutator: (arg: R, state: DraftableEntityState<T, Id>) => void) {\n  return function operation<S extends DraftableEntityState<T, Id>>(state: S, arg: R | PayloadAction<R>): S {\n    function isPayloadActionArgument(arg: R | PayloadAction<R>): arg is PayloadAction<R> {\n      return isFSA(arg);\n    }\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft);\n      } else {\n        mutator(arg, draft);\n      }\n    };\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state);\n\n      // since it's a draft, we'll just return it\n      return state;\n    }\n    return createNextState(state, runMutator);\n  };\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../immerImports';\nimport type { DraftableEntityState, EntityId, IdSelector, Update } from './models';\nexport function selectIdValue<T, Id extends EntityId>(entity: T, selectId: IdSelector<T, Id>) {\n  const key = selectId(entity);\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    console.warn('The entity passed to the `selectId` implementation returned undefined.', 'You should probably provide your own `selectId` implementation.', 'The entity that was passed:', entity, 'The `selectId` implementation:', selectId.toString());\n  }\n  return key;\n}\nexport function ensureEntitiesArray<T, Id extends EntityId>(entities: readonly T[] | Record<Id, T>): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities);\n  }\n  return entities;\n}\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}\nexport function splitAddedUpdatedEntities<T, Id extends EntityId>(newEntities: readonly T[] | Record<Id, T>, selectId: IdSelector<T, Id>, state: DraftableEntityState<T, Id>): [T[], Update<T, Id>[], Id[]] {\n  newEntities = ensureEntitiesArray(newEntities);\n  const existingIdsArray = getCurrent(state.ids);\n  const existingIds = new Set<Id>(existingIdsArray);\n  const added: T[] = [];\n  const addedIds = new Set<Id>([]);\n  const updated: Update<T, Id>[] = [];\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId);\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({\n        id,\n        changes: entity\n      });\n    } else {\n      addedIds.add(id);\n      added.push(entity);\n    }\n  }\n  return [added, updated, existingIdsArray];\n}","import type { Draft } from 'immer';\nimport type { EntityStateAdapter, IdSelector, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator, createSingleArgumentStateOperator } from './state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities } from './utils';\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (key in state.entities) {\n      return;\n    }\n    state.ids.push(key as Id & Draft<Id>);\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      addOneMutably(entity, state);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>);\n    }\n    ;\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      setOneMutably(entity, state);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.ids = [];\n    state.entities = {} as Record<Id, T>;\n    addManyMutably(newEntities, state);\n  }\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state);\n  }\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false;\n    keys.forEach(key => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key];\n        didMutate = true;\n      }\n    });\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter(id => id in state.entities) as Id[] | Draft<Id[]>;\n    }\n  }\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {}\n    });\n  }\n  function takeNewKey(keys: {\n    [id: string]: Id;\n  }, update: Update<T, Id>, state: R): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id];\n    if (original === undefined) {\n      return false;\n    }\n    const updated: T = Object.assign({}, original, update.changes);\n    const newKey = selectIdValue(updated, selectId);\n    const hasNewKey = newKey !== update.id;\n    if (hasNewKey) {\n      keys[update.id] = newKey;\n      delete (state.entities as Record<Id, T>)[update.id];\n    }\n    ;\n    (state.entities as Record<Id, T>)[newKey] = updated;\n    return hasNewKey;\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    const newKeys: {\n      [id: string]: Id;\n    } = {};\n    const updatesPerEntity: {\n      [id: string]: Update<T, Id>;\n    } = {};\n    updates.forEach(update => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes\n          }\n        };\n      }\n    });\n    updates = Object.values(updatesPerEntity);\n    const didMutateEntities = updates.length > 0;\n    if (didMutateEntities) {\n      const didMutateIds = updates.filter(update => takeNewKey(newKeys, update, state)).length > 0;\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map(e => selectIdValue(e as T, selectId));\n      }\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    addManyMutably(added, state);\n    updateManyMutably(updated, state);\n  }\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably)\n  };\n}","import type { IdSelector, Comparer, EntityStateAdapter, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator } from './state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities, getCurrent } from './utils';\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): number {\n  let lowIndex = 0;\n  let highIndex = sortedItems.length;\n  while (lowIndex < highIndex) {\n    let middleIndex = lowIndex + highIndex >>> 1;\n    const currentItem = sortedItems[middleIndex];\n    const res = comparisonFunction(item, currentItem);\n    if (res >= 0) {\n      lowIndex = middleIndex + 1;\n    } else {\n      highIndex = middleIndex;\n    }\n  }\n  return lowIndex;\n}\nexport function insert<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n  sortedItems.splice(insertAtIndex, 0, item);\n  return sortedItems;\n}\nexport function createSortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>, comparer: Comparer<T>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  const {\n    removeOne,\n    removeMany,\n    removeAll\n  } = createUnsortedStateAdapter(selectId);\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state);\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R, existingIds?: Id[]): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids));\n    const addedKeys = new Set<Id>();\n    const models = newEntities.filter(model => {\n      const modelId = selectIdValue(model, selectId);\n      const notAdded = !addedKeys.has(modelId);\n      if (notAdded) addedKeys.add(modelId);\n      return !existingKeys.has(modelId) && notAdded;\n    });\n    if (models.length !== 0) {\n      mergeFunction(state, models);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state);\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    let deduplicatedEntities = {} as Record<Id, T>;\n    newEntities = ensureEntitiesArray(newEntities);\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        const entityId = selectId(item);\n        // For multiple items with the same ID, we should keep the last one.\n        deduplicatedEntities[entityId] = item;\n        delete (state.entities as Record<Id, T>)[entityId];\n      }\n      newEntities = ensureEntitiesArray(deduplicatedEntities);\n      mergeFunction(state, newEntities);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.entities = {} as Record<Id, T>;\n    state.ids = [];\n    addManyMutably(newEntities, state, []);\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    let appliedUpdates = false;\n    let replacedIds = false;\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id];\n      if (!entity) {\n        continue;\n      }\n      appliedUpdates = true;\n      Object.assign(entity, update.changes);\n      const newId = selectId(entity);\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true;\n        delete (state.entities as Record<Id, T>)[update.id];\n        const oldIndex = (state.ids as Id[]).indexOf(update.id);\n        state.ids[oldIndex] = newId;\n        (state.entities as Record<Id, T>)[newId] = entity;\n      }\n    }\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds);\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray);\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state);\n    }\n  }\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue;\n      }\n      return false;\n    }\n    return true;\n  }\n  type MergeFunction = (state: R, addedItems: readonly T[], appliedUpdates?: boolean, replacedIds?: boolean) => void;\n  const mergeFunction: MergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n    const currentEntities = getCurrent(state.entities);\n    const currentIds = getCurrent(state.ids);\n    const stateEntities = state.entities as Record<Id, T>;\n    let ids: Iterable<Id> = currentIds;\n    if (replacedIds) {\n      ids = new Set(currentIds);\n    }\n    let sortedEntities: T[] = [];\n    for (const id of ids) {\n      const entity = currentEntities[id];\n      if (entity) {\n        sortedEntities.push(entity);\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0;\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item;\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer);\n      }\n    }\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer);\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer);\n    }\n    const newSortedIds = sortedEntities.map(selectId);\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds;\n    }\n  };\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably)\n  };\n}","import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models';\nimport { createInitialStateFactory } from './entity_state';\nimport { createSelectorsFactory } from './state_selectors';\nimport { createSortedStateAdapter } from './sorted_state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport type { WithRequiredProp } from '../tsHelpers';\nexport function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;\nexport function createEntityAdapter<T extends {\n  id: EntityId;\n}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(options: EntityAdapterOptions<T, EntityId> = {}): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options\n  };\n  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n  const stateFactory = createInitialStateFactory(stateAdapter);\n  const selectorsFactory = createSelectorsFactory<T, EntityId>();\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter\n  };\n}","import type { SerializedError } from '@reduxjs/toolkit';\nconst task = 'task';\nconst listener = 'listener';\nconst completed = 'completed';\nconst cancelled = 'cancelled';\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const;\nexport const taskCompleted = `task-${completed}` as const;\nexport const listenerCancelled = `${listener}-${cancelled}` as const;\nexport const listenerCompleted = `${listener}-${completed}` as const;\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError';\n  message: string;\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nexport const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown = (func: unknown, expected: string) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(32) : `${expected} is not a function`);\n  }\n};\nexport const noop = () => {};\nexport const catchRejection = <T,>(promise: Promise<T>, onError = noop): Promise<T> => {\n  promise.catch(onError);\n  return promise;\n};\nexport const addAbortSignalListener = (abortSignal: AbortSignal, callback: (evt: Event) => void) => {\n  abortSignal.addEventListener('abort', callback, {\n    once: true\n  });\n  return () => abortSignal.removeEventListener('abort', callback);\n};","import { TaskAbortError } from './exceptions';\nimport type { TaskResult } from './types';\nimport { addAbortSignalListener, catchRejection, noop } from './utils';\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @see {TaskAbortError}\n * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    throw new TaskAbortError(signal.reason);\n  }\n};\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(signal: AbortSignal, promise: Promise<T>): Promise<T> {\n  let cleanup = noop;\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n    if (signal.aborted) {\n      notifyRejection();\n      return;\n    }\n    cleanup = addAbortSignalListener(signal, notifyRejection);\n    promise.finally(() => cleanup()).then(resolve, reject);\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop;\n  });\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T,>(task: () => Promise<T>, cleanUp?: () => void): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve();\n    const value = await task();\n    return {\n      status: 'ok',\n      value\n    };\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error\n    };\n  } finally {\n    cleanUp?.();\n  }\n};\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T,>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(raceWithSignal(signal, promise).then(output => {\n      validateActive(signal);\n      return output;\n    }));\n  };\n};\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal);\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>(resolve => setTimeout(resolve, timeoutMs)));\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux';\nimport { isAction } from '../reduxImports';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport { createAction } from '../createAction';\nimport { nanoid } from '../nanoid';\nimport { TaskAbortError, listenerCancelled, listenerCompleted, taskCancelled, taskCompleted } from './exceptions';\nimport { createDelay, createPause, raceWithSignal, runTask, validateActive } from './task';\nimport type { AddListenerOverloads, AnyListenerPredicate, CreateListenerMiddlewareOptions, FallbackAddListenerOptions, ForkOptions, ForkedTask, ForkedTaskExecutor, ListenerEntry, ListenerErrorHandler, ListenerErrorInfo, ListenerMiddleware, ListenerMiddlewareInstance, TakePattern, TaskResult, TypedAddListener, TypedCreateListenerEntry, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\nimport { addAbortSignalListener, assertFunction, catchRejection, noop } from './utils';\nexport { TaskAbortError } from './exceptions';\nexport type { AsyncTaskExecutor, CreateListenerMiddlewareOptions, ForkedTask, ForkedTaskAPI, ForkedTaskExecutor, ListenerEffect, ListenerEffectAPI, ListenerErrorHandler, ListenerMiddleware, ListenerMiddlewareInstance, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, TypedAddListener, TypedRemoveListener, TypedStartListening, TypedStopListening, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\n\n//Overly-aggressive byte-shaving\nconst {\n  assign\n} = Object;\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const;\nconst alm = 'listenerMiddleware' as const;\nconst createFork = (parentAbortSignal: AbortSignal, parentBlockingPromises: Promise<any>[]) => {\n  const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));\n  return <T,>(taskExecutor: ForkedTaskExecutor<T>, opts?: ForkOptions): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor');\n    const childAbortController = new AbortController();\n    linkControllers(childAbortController);\n    const result = runTask<T>(async (): Promise<T> => {\n      validateActive(parentAbortSignal);\n      validateActive(childAbortController.signal);\n      const result = (await taskExecutor({\n        pause: createPause(childAbortController.signal),\n        delay: createDelay(childAbortController.signal),\n        signal: childAbortController.signal\n      })) as T;\n      validateActive(childAbortController.signal);\n      return result;\n    }, () => childAbortController.abort(taskCompleted));\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop));\n    }\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        childAbortController.abort(taskCancelled);\n      }\n    };\n  };\n};\nconst createTakePattern = <S,>(startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>, signal: AbortSignal): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>,>(predicate: P, timeout: number | undefined) => {\n    validateActive(signal);\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {};\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe();\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n        }\n      });\n      unsubscribe = () => {\n        stopListening();\n        reject();\n      };\n    });\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise];\n    if (timeout != null) {\n      promises.push(new Promise<null>(resolve => setTimeout(resolve, timeout, null)));\n    }\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises));\n      validateActive(signal);\n      return output;\n    } finally {\n      // Always clean up the listener\n      unsubscribe();\n    }\n  };\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) => catchRejection(take(predicate, timeout))) as TakePattern<S>;\n};\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let {\n    type,\n    actionCreator,\n    matcher,\n    predicate,\n    effect\n  } = options;\n  if (type) {\n    predicate = createAction(type).match;\n  } else if (actionCreator) {\n    type = actionCreator!.type;\n    predicate = actionCreator.match;\n  } else if (matcher) {\n    predicate = matcher;\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(21) : 'Creating or removing a listener requires one of the known fields for matching an action');\n  }\n  assertFunction(effect, 'options.listener');\n  return {\n    predicate,\n    type,\n    effect\n  };\n};\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> = /* @__PURE__ */assign((options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    predicate,\n    effect\n  } = getListenerEntryPropsFrom(options);\n  const entry: ListenerEntry<unknown> = {\n    id: nanoid(),\n    effect,\n    type,\n    predicate,\n    pending: new Set<AbortController>(),\n    unsubscribe: () => {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(22) : 'Unsubscribe not initialized');\n    }\n  };\n  return entry;\n}, {\n  withTypes: () => createListenerEntry\n}) as unknown as TypedCreateListenerEntry<unknown>;\nconst findListenerEntry = (listenerMap: Map<string, ListenerEntry>, options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    effect,\n    predicate\n  } = getListenerEntryPropsFrom(options);\n  return Array.from(listenerMap.values()).find(entry => {\n    const matchPredicateOrType = typeof type === 'string' ? entry.type === type : entry.predicate === predicate;\n    return matchPredicateOrType && entry.effect === effect;\n  });\n};\nconst cancelActiveListeners = (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>) => {\n  entry.pending.forEach(controller => {\n    controller.abort(listenerCancelled);\n  });\n};\nconst createClearListenerMiddleware = (listenerMap: Map<string, ListenerEntry>, executingListeners: Map<ListenerEntry, number>) => {\n  return () => {\n    for (const listener of executingListeners.keys()) {\n      cancelActiveListeners(listener);\n    }\n    listenerMap.clear();\n  };\n};\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (errorHandler: ListenerErrorHandler, errorToNotify: unknown, errorInfo: ListenerErrorInfo): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo);\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError;\n    }, 0);\n  }\n};\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/add`), {\n  withTypes: () => addListener\n}) as unknown as TypedAddListener<unknown>;\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */createAction(`${alm}/removeAll`);\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/remove`), {\n  withTypes: () => removeListener\n}) as unknown as TypedRemoveListener<unknown>;\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args);\n};\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {}) => {\n  const listenerMap = new Map<string, ListenerEntry>();\n\n  // Track listeners whose effect is currently executing so clearListeners can\n  // abort even listeners that have become unsubscribed while executing.\n  const executingListeners = new Map<ListenerEntry, number>();\n  const trackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 0;\n    executingListeners.set(entry, count + 1);\n  };\n  const untrackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 1;\n    if (count === 1) {\n      executingListeners.delete(entry);\n    } else {\n      executingListeners.set(entry, count - 1);\n    }\n  };\n  const {\n    extra,\n    onError = defaultErrorHandler\n  } = middlewareOptions;\n  assertFunction(onError, 'onError');\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id);\n    listenerMap.set(entry.id, entry);\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe();\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    };\n  };\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options as any);\n    return insertEntry(entry);\n  }) as AddListenerOverloads<any>;\n  assign(startListening, {\n    withTypes: () => startListening\n  });\n  const stopListening = (options: FallbackAddListenerOptions & UnsubscribeListenerOptions): boolean => {\n    const entry = findListenerEntry(listenerMap, options);\n    if (entry) {\n      entry.unsubscribe();\n      if (options.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    }\n    return !!entry;\n  };\n  assign(stopListening, {\n    withTypes: () => stopListening\n  });\n  const notifyListener = async (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>, action: unknown, api: MiddlewareAPI, getOriginalState: () => StateType) => {\n    const internalTaskController = new AbortController();\n    const take = createTakePattern(startListening as AddListenerOverloads<any>, internalTaskController.signal);\n    const autoJoinPromises: Promise<any>[] = [];\n    try {\n      entry.pending.add(internalTaskController);\n      trackExecutingListener(entry);\n      await Promise.resolve(entry.effect(action,\n      // Use assign() rather than ... to avoid extra helper functions added to bundle\n      assign({}, api, {\n        getOriginalState,\n        condition: (predicate: AnyListenerPredicate<any>, timeout?: number) => take(predicate, timeout).then(Boolean),\n        take,\n        delay: createDelay(internalTaskController.signal),\n        pause: createPause<any>(internalTaskController.signal),\n        extra,\n        signal: internalTaskController.signal,\n        fork: createFork(internalTaskController.signal, autoJoinPromises),\n        unsubscribe: entry.unsubscribe,\n        subscribe: () => {\n          listenerMap.set(entry.id, entry);\n        },\n        cancelActiveListeners: () => {\n          entry.pending.forEach((controller, _, set) => {\n            if (controller !== internalTaskController) {\n              controller.abort(listenerCancelled);\n              set.delete(controller);\n            }\n          });\n        },\n        cancel: () => {\n          internalTaskController.abort(listenerCancelled);\n          entry.pending.delete(internalTaskController);\n        },\n        throwIfCancelled: () => {\n          validateActive(internalTaskController.signal);\n        }\n      })));\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect'\n        });\n      }\n    } finally {\n      await Promise.all(autoJoinPromises);\n      internalTaskController.abort(listenerCompleted); // Notify that the task has completed\n      untrackExecutingListener(entry);\n      entry.pending.delete(internalTaskController);\n    }\n  };\n  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);\n  const middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument> = api => next => action => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action);\n    }\n    if (addListener.match(action)) {\n      return startListening(action.payload as any);\n    }\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware();\n      return;\n    }\n    if (removeListener.match(action)) {\n      return stopListening(action.payload);\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState();\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);\n      }\n      return originalState as StateType;\n    };\n    let result: unknown;\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action);\n      if (listenerMap.size > 0) {\n        const currentState = api.getState();\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values());\n        for (const entry of listenerEntries) {\n          let runListener = false;\n          try {\n            runListener = entry.predicate(action, currentState, originalState);\n          } catch (predicateError) {\n            runListener = false;\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate'\n            });\n          }\n          if (!runListener) {\n            continue;\n          }\n          notifyListener(entry, action, api, getOriginalState);\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN;\n    }\n    return result;\n  };\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;\n};","import type { Dispatch, Middleware, UnknownAction } from 'redux';\nimport { compose } from '../reduxImports';\nimport { createAction } from '../createAction';\nimport { isAllOf } from '../matchers';\nimport { nanoid } from '../nanoid';\nimport { getOrInsertComputed } from '../utils';\nimport type { AddMiddleware, DynamicMiddleware, DynamicMiddlewareInstance, MiddlewareEntry, WithMiddleware } from './types';\nexport type { DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './types';\nconst createMiddlewareEntry = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(middleware: Middleware<any, State, DispatchType>): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map()\n});\nconst matchInstance = (instanceId: string) => (action: any): action is {\n  meta: {\n    instanceId: string;\n  };\n} => action?.meta?.instanceId === instanceId;\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid();\n  const middlewareMap = new Map<Middleware<any, State, DispatchType>, MiddlewareEntry<State, DispatchType>>();\n  const withMiddleware = Object.assign(createAction('dynamicMiddleware/add', (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n    payload: middlewares,\n    meta: {\n      instanceId\n    }\n  })), {\n    withTypes: () => withMiddleware\n  }) as WithMiddleware<State, DispatchType>;\n  const addMiddleware = Object.assign(function addMiddleware(...middlewares: Middleware<any, State, DispatchType>[]) {\n    middlewares.forEach(middleware => {\n      getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);\n    });\n  }, {\n    withTypes: () => addMiddleware\n  }) as AddMiddleware<State, DispatchType>;\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = api => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map(entry => getOrInsertComputed(entry.applied, api, entry.middleware));\n    return compose(...appliedMiddleware);\n  };\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n  const middleware: DynamicMiddleware<State, DispatchType> = api => next => action => {\n    if (isWithMiddleware(action)) {\n      addMiddleware(...action.payload);\n      return api.dispatch;\n    }\n    return getFinalMiddleware(api)(next)(action);\n  };\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { PreloadedStateShapeFromReducersMapObject, Reducer, StateFromReducersMapObject, UnknownAction } from 'redux';\nimport { combineReducers } from 'redux';\nimport { nanoid } from './nanoid';\nimport type { Id, NonUndefined, Tail, UnionToIntersection, WithOptionalProp } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\ntype SliceLike<ReducerPath extends string, State, PreloadedState = State> = {\n  reducerPath: ReducerPath;\n  reducer: Reducer<State, any, PreloadedState>;\n};\ntype AnySliceLike = SliceLike<string, any>;\ntype SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;\ntype SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;\ntype SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;\nexport type WithSlice<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikeState<A> };\nexport type WithSlicePreloadedState<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A> };\ntype ReducerMap = Record<string, Reducer>;\ntype ExistingSliceLike<DeclaredState, PreloadedState> = { [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>> }[keyof DeclaredState];\nexport type InjectConfig = {\n  /**\n   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.\n   */\n  overrideExisting?: boolean;\n};\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;\n  };\n}\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;\ntype InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;\nconst isSliceLike = (maybeSliceLike: AnySliceLike | ReducerMap): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string';\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) => slices.flatMap<[string, Reducer]>(sliceOrMap => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original');\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE];\nconst stateProxyMap = new WeakMap<object, object>();\nconst createStateProxy = <State extends object,>(state: State, reducerMap: Partial<Record<PropertyKey, Reducer>>, initialStateCache: Record<PropertyKey, unknown>) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {\n  get: (target, prop, receiver) => {\n    if (prop === ORIGINAL_STATE) return target;\n    const result = Reflect.get(target, prop, receiver);\n    if (typeof result === 'undefined') {\n      const cached = initialStateCache[prop];\n      if (typeof cached !== 'undefined') return cached;\n      const reducer = reducerMap[prop];\n      if (reducer) {\n        // ensure action type is random, to prevent reducer treating it differently\n        const reducerResult = reducer(undefined, {\n          type: nanoid()\n        });\n        if (typeof reducerResult === 'undefined') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). ` + `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + `you can use null instead of undefined.`);\n        }\n        initialStateCache[prop] = reducerResult;\n        return reducerResult;\n      }\n    }\n    return result;\n  }\n})) as State;\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(25) : 'original must be used on state Proxy');\n  }\n  return state[ORIGINAL_STATE];\n};\nconst emptyObject = {};\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state;\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>> {\n  const reducerMap = Object.fromEntries(getReducers(slices));\n  const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;\n  let reducer = getReducer();\n  function combinedReducer(state: Record<string, unknown>, action: UnknownAction) {\n    return reducer(state, action);\n  }\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n  const initialStateCache: Record<PropertyKey, unknown> = {};\n  const inject = (slice: AnySliceLike, config: InjectConfig = {}): typeof combinedReducer => {\n    const {\n      reducerPath,\n      reducer: reducerToInject\n    } = slice;\n    const currentReducer = reducerMap[reducerPath];\n    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n      }\n      return combinedReducer;\n    }\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath];\n    }\n    reducerMap[reducerPath] = reducerToInject;\n    reducer = getReducer();\n    return combinedReducer;\n  };\n  const selector = Object.assign(function makeSelector<State extends object, RootState, Args extends any[]>(selectorFn: (state: State, ...args: Args) => any, selectState?: (rootState: RootState, ...args: Args) => State) {\n    return function selector(state: State, ...args: Args) {\n      return selectorFn(createStateProxy(selectState ? selectState(state as any, ...args) : state, reducerMap, initialStateCache), ...args);\n    };\n  }, {\n    original\n  });\n  return Object.assign(combinedReducer, {\n    inject,\n    selector\n  }) as any;\n}","/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` + 'use the non-minified dev environment for full errors. ';\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,cAAc;AACd,SAAS,QAAQ,YAAAA,iBAAgB;;;ACJjC,SAAS,SAAS,SAAoB,SAAiB,aAAa,6BAA6B;;;ADOjG,SAAS,gBAAgB,kBAAkB;;;AEP3C,SAAS,uBAAuB,sBAAsB;;;ACE/C,IAAM,iCAA+D,IAAI,SAAoB;AAClG,QAAMC,kBAAkB,sBAA8B,GAAG,IAAI;AAC7D,QAAMC,2BAA0B,OAAO,OAAO,IAAIC,UAAoB;AACpE,UAAM,WAAWF,gBAAe,GAAGE,KAAI;AACvC,UAAM,kBA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AA,MACJ;AAAA,MACA,SAAS;AAAA,IACX,IAAI;AACJ,UAAM,iBAAiB,WAAW,WAAW;AAC7C,QAAI,CAAC,OAAO,oBAAoB,kBAAkB,mBAAmB,iBAAiB;AACpF,UAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,aAAa,eAAe;AAC5E,gBAAQ,MAAM,0DAA0D,WAAW,gDAAgD;AAAA,MACrI;AACA,aAAO;AAAA,IACT;AACA,QAAI,OAAO,oBAAoB,mBAAmB,iBAAiB;AACjE,aAAO,kBAAkB,WAAW;AAAA,IACtC;AACA,eAAW,WAAW,IAAI;AAC1B,cAAU,WAAW;AACrB,WAAO;AAAA,EACT;AACA,QAAM,WAAW,OAAO,OAAO,SAAS,aAAkE,YAAkD,aAA8D;AACxN,WAAO,SAASC,UAAS,UAAiB,MAAY;AACpD,aAAO,WAAW,iBAAiB,cAAc,YAAY,OAAc,GAAG,IAAI,IAAI,OAAO,YAAY,iBAAiB,GAAG,GAAG,IAAI;AAAA,IACtI;AAAA,EACF,GAAG;AAAA,IACD;AAAA,EACF,CAAC;AACD,SAAO,OAAO,OAAO,iBAAiB;AAAA,IACpC;AAAA,IACA;AAAA,EACF,CAAC;AACH;;;AC9SO,SAAS,uBAAuB,MAAc;AACnD,SAAO,iCAAiC,IAAI,oDAAoD,IAAI;AACtG;","names":["original","createSelector","createDraftSafeSelector","args","noop","isActionCreator","stringify","getSerialize","listener","middleware","reducer","createAsyncThunk","ReducerType","createSlice","reducer","name","reducerPath","_a","createSelector","arg","original","noop","noop","task","result","noop","listener","addMiddleware","middleware","combineReducers","combineReducers","selector"]}
Index: node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2311 @@
+// src/index.ts
+export * from "redux";
+import { freeze, original as original2 } from "immer";
+
+// src/immerImports.ts
+import { current, isDraft, produce, isDraftable, setUseStrictIteration } from "immer";
+
+// src/index.ts
+import { createSelector, lruMemoize } from "reselect";
+
+// src/reselectImports.ts
+import { createSelectorCreator, weakMapMemoize } from "reselect";
+
+// src/createDraftSafeSelector.ts
+var createDraftSafeSelectorCreator = (...args) => {
+  const createSelector2 = createSelectorCreator(...args);
+  const createDraftSafeSelector2 = Object.assign((...args2) => {
+    const selector = createSelector2(...args2);
+    const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
+    Object.assign(wrappedSelector, selector);
+    return wrappedSelector;
+  }, {
+    withTypes: () => createDraftSafeSelector2
+  });
+  return createDraftSafeSelector2;
+};
+var createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(weakMapMemoize);
+
+// src/reduxImports.ts
+import { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from "redux";
+
+// src/devtoolsExtension.ts
+var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
+  if (arguments.length === 0) return void 0;
+  if (typeof arguments[0] === "object") return compose;
+  return compose.apply(null, arguments);
+};
+var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
+  return function(noop3) {
+    return noop3;
+  };
+};
+
+// src/getDefaultMiddleware.ts
+import { thunk as thunkMiddleware, withExtraArgument } from "redux-thunk";
+
+// src/tsHelpers.ts
+var hasMatchFunction = (v) => {
+  return v && typeof v.match === "function";
+};
+
+// src/createAction.ts
+function createAction(type, prepareAction) {
+  function actionCreator(...args) {
+    if (prepareAction) {
+      let prepared = prepareAction(...args);
+      if (!prepared) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
+      }
+      return {
+        type,
+        payload: prepared.payload,
+        ..."meta" in prepared && {
+          meta: prepared.meta
+        },
+        ..."error" in prepared && {
+          error: prepared.error
+        }
+      };
+    }
+    return {
+      type,
+      payload: args[0]
+    };
+  }
+  actionCreator.toString = () => `${type}`;
+  actionCreator.type = type;
+  actionCreator.match = (action) => isAction(action) && action.type === type;
+  return actionCreator;
+}
+function isActionCreator(action) {
+  return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
+  hasMatchFunction(action);
+}
+function isFSA(action) {
+  return isAction(action) && Object.keys(action).every(isValidKey);
+}
+function isValidKey(key) {
+  return ["type", "payload", "error", "meta"].indexOf(key) > -1;
+}
+
+// src/actionCreatorInvariantMiddleware.ts
+function getMessage(type) {
+  const splitType = type ? `${type}`.split("/") : [];
+  const actionName = splitType[splitType.length - 1] || "actionCreator";
+  return `Detected an action creator with type "${type || "unknown"}" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`;
+}
+function createActionCreatorInvariantMiddleware(options = {}) {
+  if (process.env.NODE_ENV === "production") {
+    return () => (next) => (action) => next(action);
+  }
+  const {
+    isActionCreator: isActionCreator2 = isActionCreator
+  } = options;
+  return () => (next) => (action) => {
+    if (isActionCreator2(action)) {
+      console.warn(getMessage(action.type));
+    }
+    return next(action);
+  };
+}
+
+// src/utils.ts
+function getTimeMeasureUtils(maxDelay, fnName) {
+  let elapsed = 0;
+  return {
+    measureTime(fn) {
+      const started = Date.now();
+      try {
+        return fn();
+      } finally {
+        const finished = Date.now();
+        elapsed += finished - started;
+      }
+    },
+    warnIfExceeded() {
+      if (elapsed > maxDelay) {
+        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. 
+If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
+It is disabled in production builds, so you don't need to worry about that.`);
+      }
+    }
+  };
+}
+var Tuple = class _Tuple extends Array {
+  constructor(...items) {
+    super(...items);
+    Object.setPrototypeOf(this, _Tuple.prototype);
+  }
+  static get [Symbol.species]() {
+    return _Tuple;
+  }
+  concat(...arr) {
+    return super.concat.apply(this, arr);
+  }
+  prepend(...arr) {
+    if (arr.length === 1 && Array.isArray(arr[0])) {
+      return new _Tuple(...arr[0].concat(this));
+    }
+    return new _Tuple(...arr.concat(this));
+  }
+};
+function freezeDraftable(val) {
+  return isDraftable(val) ? produce(val, () => {
+  }) : val;
+}
+function getOrInsertComputed(map, key, compute) {
+  if (map.has(key)) return map.get(key);
+  return map.set(key, compute(key)).get(key);
+}
+
+// src/immutableStateInvariantMiddleware.ts
+function isImmutableDefault(value) {
+  return typeof value !== "object" || value == null || Object.isFrozen(value);
+}
+function trackForMutations(isImmutable, ignoredPaths, obj) {
+  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);
+  return {
+    detectMutations() {
+      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);
+    }
+  };
+}
+function trackProperties(isImmutable, ignoredPaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
+  const tracked = {
+    value: obj
+  };
+  if (!isImmutable(obj) && !checkedObjects.has(obj)) {
+    checkedObjects.add(obj);
+    tracked.children = {};
+    const hasIgnoredPaths = ignoredPaths.length > 0;
+    for (const key in obj) {
+      const nestedPath = path ? path + "." + key : key;
+      if (hasIgnoredPaths) {
+        const hasMatches = ignoredPaths.some((ignored) => {
+          if (ignored instanceof RegExp) {
+            return ignored.test(nestedPath);
+          }
+          return nestedPath === ignored;
+        });
+        if (hasMatches) {
+          continue;
+        }
+      }
+      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);
+    }
+  }
+  return tracked;
+}
+function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
+  const prevObj = trackedProperty ? trackedProperty.value : void 0;
+  const sameRef = prevObj === obj;
+  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
+    return {
+      wasMutated: true,
+      path
+    };
+  }
+  if (isImmutable(prevObj) || isImmutable(obj)) {
+    return {
+      wasMutated: false
+    };
+  }
+  const keysToDetect = {};
+  for (let key in trackedProperty.children) {
+    keysToDetect[key] = true;
+  }
+  for (let key in obj) {
+    keysToDetect[key] = true;
+  }
+  const hasIgnoredPaths = ignoredPaths.length > 0;
+  for (let key in keysToDetect) {
+    const nestedPath = path ? path + "." + key : key;
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath);
+        }
+        return nestedPath === ignored;
+      });
+      if (hasMatches) {
+        continue;
+      }
+    }
+    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
+    if (result.wasMutated) {
+      return result;
+    }
+  }
+  return {
+    wasMutated: false
+  };
+}
+function createImmutableStateInvariantMiddleware(options = {}) {
+  if (process.env.NODE_ENV === "production") {
+    return () => (next) => (action) => next(action);
+  } else {
+    let stringify2 = function(obj, serializer, indent, decycler) {
+      return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
+    }, getSerialize2 = function(serializer, decycler) {
+      let stack = [], keys = [];
+      if (!decycler) decycler = function(_, value) {
+        if (stack[0] === value) return "[Circular ~]";
+        return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
+      };
+      return function(key, value) {
+        if (stack.length > 0) {
+          var thisPos = stack.indexOf(this);
+          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
+          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
+          if (~stack.indexOf(value)) value = decycler.call(this, key, value);
+        } else stack.push(value);
+        return serializer == null ? value : serializer.call(this, key, value);
+      };
+    };
+    var stringify = stringify2, getSerialize = getSerialize2;
+    let {
+      isImmutable = isImmutableDefault,
+      ignoredPaths,
+      warnAfter = 32
+    } = options;
+    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
+    return ({
+      getState
+    }) => {
+      let state = getState();
+      let tracker = track(state);
+      let result;
+      return (next) => (action) => {
+        const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
+        measureUtils.measureTime(() => {
+          state = getState();
+          result = tracker.detectMutations();
+          tracker = track(state);
+          if (result.wasMutated) {
+            throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
+          }
+        });
+        const dispatchedAction = next(action);
+        measureUtils.measureTime(() => {
+          state = getState();
+          result = tracker.detectMutations();
+          tracker = track(state);
+          if (result.wasMutated) {
+            throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
+          }
+        });
+        measureUtils.warnIfExceeded();
+        return dispatchedAction;
+      };
+    };
+  }
+}
+
+// src/serializableStateInvariantMiddleware.ts
+function isPlain(val) {
+  const type = typeof val;
+  return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
+}
+function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
+  let foundNestedSerializable;
+  if (!isSerializable(value)) {
+    return {
+      keyPath: path || "<root>",
+      value
+    };
+  }
+  if (typeof value !== "object" || value === null) {
+    return false;
+  }
+  if (cache?.has(value)) return false;
+  const entries = getEntries != null ? getEntries(value) : Object.entries(value);
+  const hasIgnoredPaths = ignoredPaths.length > 0;
+  for (const [key, nestedValue] of entries) {
+    const nestedPath = path ? path + "." + key : key;
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath);
+        }
+        return nestedPath === ignored;
+      });
+      if (hasMatches) {
+        continue;
+      }
+    }
+    if (!isSerializable(nestedValue)) {
+      return {
+        keyPath: nestedPath,
+        value: nestedValue
+      };
+    }
+    if (typeof nestedValue === "object") {
+      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
+      if (foundNestedSerializable) {
+        return foundNestedSerializable;
+      }
+    }
+  }
+  if (cache && isNestedFrozen(value)) cache.add(value);
+  return false;
+}
+function isNestedFrozen(value) {
+  if (!Object.isFrozen(value)) return false;
+  for (const nestedValue of Object.values(value)) {
+    if (typeof nestedValue !== "object" || nestedValue === null) continue;
+    if (!isNestedFrozen(nestedValue)) return false;
+  }
+  return true;
+}
+function createSerializableStateInvariantMiddleware(options = {}) {
+  if (process.env.NODE_ENV === "production") {
+    return () => (next) => (action) => next(action);
+  } else {
+    const {
+      isSerializable = isPlain,
+      getEntries,
+      ignoredActions = [],
+      ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
+      ignoredPaths = [],
+      warnAfter = 32,
+      ignoreState = false,
+      ignoreActions = false,
+      disableCache = false
+    } = options;
+    const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
+    return (storeAPI) => (next) => (action) => {
+      if (!isAction(action)) {
+        return next(action);
+      }
+      const result = next(action);
+      const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
+      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
+        measureUtils.measureTime(() => {
+          const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
+          if (foundActionNonSerializableValue) {
+            const {
+              keyPath,
+              value
+            } = foundActionNonSerializableValue;
+            console.error(`A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`, value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
+          }
+        });
+      }
+      if (!ignoreState) {
+        measureUtils.measureTime(() => {
+          const state = storeAPI.getState();
+          const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
+          if (foundStateNonSerializableValue) {
+            const {
+              keyPath,
+              value
+            } = foundStateNonSerializableValue;
+            console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
+Take a look at the reducer(s) handling this action type: ${action.type}.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
+          }
+        });
+        measureUtils.warnIfExceeded();
+      }
+      return result;
+    };
+  }
+}
+
+// src/getDefaultMiddleware.ts
+function isBoolean(x) {
+  return typeof x === "boolean";
+}
+var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
+  const {
+    thunk = true,
+    immutableCheck = true,
+    serializableCheck = true,
+    actionCreatorCheck = true
+  } = options ?? {};
+  let middlewareArray = new Tuple();
+  if (thunk) {
+    if (isBoolean(thunk)) {
+      middlewareArray.push(thunkMiddleware);
+    } else {
+      middlewareArray.push(withExtraArgument(thunk.extraArgument));
+    }
+  }
+  if (process.env.NODE_ENV !== "production") {
+    if (immutableCheck) {
+      let immutableOptions = {};
+      if (!isBoolean(immutableCheck)) {
+        immutableOptions = immutableCheck;
+      }
+      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
+    }
+    if (serializableCheck) {
+      let serializableOptions = {};
+      if (!isBoolean(serializableCheck)) {
+        serializableOptions = serializableCheck;
+      }
+      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
+    }
+    if (actionCreatorCheck) {
+      let actionCreatorOptions = {};
+      if (!isBoolean(actionCreatorCheck)) {
+        actionCreatorOptions = actionCreatorCheck;
+      }
+      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
+    }
+  }
+  return middlewareArray;
+};
+
+// src/autoBatchEnhancer.ts
+var SHOULD_AUTOBATCH = "RTK_autoBatch";
+var prepareAutoBatched = () => (payload) => ({
+  payload,
+  meta: {
+    [SHOULD_AUTOBATCH]: true
+  }
+});
+var createQueueWithTimer = (timeout) => {
+  return (notify) => {
+    setTimeout(notify, timeout);
+  };
+};
+var autoBatchEnhancer = (options = {
+  type: "raf"
+}) => (next) => (...args) => {
+  const store = next(...args);
+  let notifying = true;
+  let shouldNotifyAtEndOfTick = false;
+  let notificationQueued = false;
+  const listeners = /* @__PURE__ */ new Set();
+  const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? (
+    // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
+    typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10)
+  ) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
+  const notifyListeners = () => {
+    notificationQueued = false;
+    if (shouldNotifyAtEndOfTick) {
+      shouldNotifyAtEndOfTick = false;
+      listeners.forEach((l) => l());
+    }
+  };
+  return Object.assign({}, store, {
+    // Override the base `store.subscribe` method to keep original listeners
+    // from running if we're delaying notifications
+    subscribe(listener2) {
+      const wrappedListener = () => notifying && listener2();
+      const unsubscribe = store.subscribe(wrappedListener);
+      listeners.add(listener2);
+      return () => {
+        unsubscribe();
+        listeners.delete(listener2);
+      };
+    },
+    // Override the base `store.dispatch` method so that we can check actions
+    // for the `shouldAutoBatch` flag and determine if batching is active
+    dispatch(action) {
+      try {
+        notifying = !action?.meta?.[SHOULD_AUTOBATCH];
+        shouldNotifyAtEndOfTick = !notifying;
+        if (shouldNotifyAtEndOfTick) {
+          if (!notificationQueued) {
+            notificationQueued = true;
+            queueCallback(notifyListeners);
+          }
+        }
+        return store.dispatch(action);
+      } finally {
+        notifying = true;
+      }
+    }
+  });
+};
+
+// src/getDefaultEnhancers.ts
+var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
+  const {
+    autoBatch = true
+  } = options ?? {};
+  let enhancerArray = new Tuple(middlewareEnhancer);
+  if (autoBatch) {
+    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
+  }
+  return enhancerArray;
+};
+
+// src/configureStore.ts
+function configureStore(options) {
+  const getDefaultMiddleware = buildGetDefaultMiddleware();
+  const {
+    reducer = void 0,
+    middleware,
+    devTools = true,
+    duplicateMiddlewareCheck = true,
+    preloadedState = void 0,
+    enhancers = void 0
+  } = options || {};
+  let rootReducer;
+  if (typeof reducer === "function") {
+    rootReducer = reducer;
+  } else if (isPlainObject(reducer)) {
+    rootReducer = combineReducers(reducer);
+  } else {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
+  }
+  if (process.env.NODE_ENV !== "production" && middleware && typeof middleware !== "function") {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
+  }
+  let finalMiddleware;
+  if (typeof middleware === "function") {
+    finalMiddleware = middleware(getDefaultMiddleware);
+    if (process.env.NODE_ENV !== "production" && !Array.isArray(finalMiddleware)) {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
+    }
+  } else {
+    finalMiddleware = getDefaultMiddleware();
+  }
+  if (process.env.NODE_ENV !== "production" && finalMiddleware.some((item) => typeof item !== "function")) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
+  }
+  if (process.env.NODE_ENV !== "production" && duplicateMiddlewareCheck) {
+    let middlewareReferences = /* @__PURE__ */ new Set();
+    finalMiddleware.forEach((middleware2) => {
+      if (middlewareReferences.has(middleware2)) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(42) : "Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");
+      }
+      middlewareReferences.add(middleware2);
+    });
+  }
+  let finalCompose = compose;
+  if (devTools) {
+    finalCompose = composeWithDevTools({
+      // Enable capture of stack traces for dispatched Redux actions
+      trace: process.env.NODE_ENV !== "production",
+      ...typeof devTools === "object" && devTools
+    });
+  }
+  const middlewareEnhancer = applyMiddleware(...finalMiddleware);
+  const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
+  if (process.env.NODE_ENV !== "production" && enhancers && typeof enhancers !== "function") {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
+  }
+  let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
+  if (process.env.NODE_ENV !== "production" && !Array.isArray(storeEnhancers)) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
+  }
+  if (process.env.NODE_ENV !== "production" && storeEnhancers.some((item) => typeof item !== "function")) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
+  }
+  if (process.env.NODE_ENV !== "production" && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
+    console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
+  }
+  const composedEnhancer = finalCompose(...storeEnhancers);
+  return createStore(rootReducer, preloadedState, composedEnhancer);
+}
+
+// src/mapBuilders.ts
+function executeReducerBuilderCallback(builderCallback) {
+  const actionsMap = {};
+  const actionMatchers = [];
+  let defaultCaseReducer;
+  const builder = {
+    addCase(typeOrActionCreator, reducer) {
+      if (process.env.NODE_ENV !== "production") {
+        if (actionMatchers.length > 0) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
+        }
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
+      if (!type) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
+      }
+      if (type in actionsMap) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
+      }
+      actionsMap[type] = reducer;
+      return builder;
+    },
+    addAsyncThunk(asyncThunk, reducers) {
+      if (process.env.NODE_ENV !== "production") {
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(43) : "`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
+      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
+      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
+      if (reducers.settled) actionMatchers.push({
+        matcher: asyncThunk.settled,
+        reducer: reducers.settled
+      });
+      return builder;
+    },
+    addMatcher(matcher, reducer) {
+      if (process.env.NODE_ENV !== "production") {
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
+        }
+      }
+      actionMatchers.push({
+        matcher,
+        reducer
+      });
+      return builder;
+    },
+    addDefaultCase(reducer) {
+      if (process.env.NODE_ENV !== "production") {
+        if (defaultCaseReducer) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
+        }
+      }
+      defaultCaseReducer = reducer;
+      return builder;
+    }
+  };
+  builderCallback(builder);
+  return [actionsMap, actionMatchers, defaultCaseReducer];
+}
+
+// src/createReducer.ts
+function isStateFunction(x) {
+  return typeof x === "function";
+}
+function createReducer(initialState, mapOrBuilderCallback) {
+  if (process.env.NODE_ENV !== "production") {
+    if (typeof mapOrBuilderCallback === "object") {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
+    }
+  }
+  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
+  let getInitialState;
+  if (isStateFunction(initialState)) {
+    getInitialState = () => freezeDraftable(initialState());
+  } else {
+    const frozenInitialState = freezeDraftable(initialState);
+    getInitialState = () => frozenInitialState;
+  }
+  function reducer(state = getInitialState(), action) {
+    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
+      matcher
+    }) => matcher(action)).map(({
+      reducer: reducer2
+    }) => reducer2)];
+    if (caseReducers.filter((cr) => !!cr).length === 0) {
+      caseReducers = [finalDefaultCaseReducer];
+    }
+    return caseReducers.reduce((previousState, caseReducer) => {
+      if (caseReducer) {
+        if (isDraft(previousState)) {
+          const draft = previousState;
+          const result = caseReducer(draft, action);
+          if (result === void 0) {
+            return previousState;
+          }
+          return result;
+        } else if (!isDraftable(previousState)) {
+          const result = caseReducer(previousState, action);
+          if (result === void 0) {
+            if (previousState === null) {
+              return previousState;
+            }
+            throw Error("A case reducer on a non-draftable value must not return undefined");
+          }
+          return result;
+        } else {
+          return produce(previousState, (draft) => {
+            return caseReducer(draft, action);
+          });
+        }
+      }
+      return previousState;
+    }, state);
+  }
+  reducer.getInitialState = getInitialState;
+  return reducer;
+}
+
+// src/matchers.ts
+var matches = (matcher, action) => {
+  if (hasMatchFunction(matcher)) {
+    return matcher.match(action);
+  } else {
+    return matcher(action);
+  }
+};
+function isAnyOf(...matchers) {
+  return (action) => {
+    return matchers.some((matcher) => matches(matcher, action));
+  };
+}
+function isAllOf(...matchers) {
+  return (action) => {
+    return matchers.every((matcher) => matches(matcher, action));
+  };
+}
+function hasExpectedRequestMetadata(action, validStatus) {
+  if (!action || !action.meta) return false;
+  const hasValidRequestId = typeof action.meta.requestId === "string";
+  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
+  return hasValidRequestId && hasValidRequestStatus;
+}
+function isAsyncThunkArray(a) {
+  return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
+}
+function isPending(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["pending"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isPending()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
+}
+function isRejected(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejected()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
+}
+function isRejectedWithValue(...asyncThunks) {
+  const hasFlag = (action) => {
+    return action && action.meta && action.meta.rejectedWithValue;
+  };
+  if (asyncThunks.length === 0) {
+    return isAllOf(isRejected(...asyncThunks), hasFlag);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejectedWithValue()(asyncThunks[0]);
+  }
+  return isAllOf(isRejected(...asyncThunks), hasFlag);
+}
+function isFulfilled(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isFulfilled()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
+}
+function isAsyncThunkAction(...asyncThunks) {
+  if (asyncThunks.length === 0) {
+    return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
+  }
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isAsyncThunkAction()(asyncThunks[0]);
+  }
+  return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));
+}
+
+// src/nanoid.ts
+var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
+var nanoid = (size = 21) => {
+  let id = "";
+  let i = size;
+  while (i--) {
+    id += urlAlphabet[Math.random() * 64 | 0];
+  }
+  return id;
+};
+
+// src/createAsyncThunk.ts
+var commonProperties = ["name", "message", "stack", "code"];
+var RejectWithValue = class {
+  constructor(payload, meta) {
+    this.payload = payload;
+    this.meta = meta;
+  }
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  _type;
+};
+var FulfillWithMeta = class {
+  constructor(payload, meta) {
+    this.payload = payload;
+    this.meta = meta;
+  }
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  _type;
+};
+var miniSerializeError = (value) => {
+  if (typeof value === "object" && value !== null) {
+    const simpleError = {};
+    for (const property of commonProperties) {
+      if (typeof value[property] === "string") {
+        simpleError[property] = value[property];
+      }
+    }
+    return simpleError;
+  }
+  return {
+    message: String(value)
+  };
+};
+var externalAbortMessage = "External signal was aborted";
+var createAsyncThunk = /* @__PURE__ */ (() => {
+  function createAsyncThunk2(typePrefix, payloadCreator, options) {
+    const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
+      payload,
+      meta: {
+        ...meta || {},
+        arg,
+        requestId,
+        requestStatus: "fulfilled"
+      }
+    }));
+    const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
+      payload: void 0,
+      meta: {
+        ...meta || {},
+        arg,
+        requestId,
+        requestStatus: "pending"
+      }
+    }));
+    const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
+      payload,
+      error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
+      meta: {
+        ...meta || {},
+        arg,
+        requestId,
+        rejectedWithValue: !!payload,
+        requestStatus: "rejected",
+        aborted: error?.name === "AbortError",
+        condition: error?.name === "ConditionError"
+      }
+    }));
+    function actionCreator(arg, {
+      signal
+    } = {}) {
+      return (dispatch, getState, extra) => {
+        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();
+        const abortController = new AbortController();
+        let abortHandler;
+        let abortReason;
+        function abort(reason) {
+          abortReason = reason;
+          abortController.abort();
+        }
+        if (signal) {
+          if (signal.aborted) {
+            abort(externalAbortMessage);
+          } else {
+            signal.addEventListener("abort", () => abort(externalAbortMessage), {
+              once: true
+            });
+          }
+        }
+        const promise = async function() {
+          let finalAction;
+          try {
+            let conditionResult = options?.condition?.(arg, {
+              getState,
+              extra
+            });
+            if (isThenable(conditionResult)) {
+              conditionResult = await conditionResult;
+            }
+            if (conditionResult === false || abortController.signal.aborted) {
+              throw {
+                name: "ConditionError",
+                message: "Aborted due to condition callback returning false."
+              };
+            }
+            const abortedPromise = new Promise((_, reject) => {
+              abortHandler = () => {
+                reject({
+                  name: "AbortError",
+                  message: abortReason || "Aborted"
+                });
+              };
+              abortController.signal.addEventListener("abort", abortHandler, {
+                once: true
+              });
+            });
+            dispatch(pending(requestId, arg, options?.getPendingMeta?.({
+              requestId,
+              arg
+            }, {
+              getState,
+              extra
+            })));
+            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
+              dispatch,
+              getState,
+              extra,
+              requestId,
+              signal: abortController.signal,
+              abort,
+              rejectWithValue: (value, meta) => {
+                return new RejectWithValue(value, meta);
+              },
+              fulfillWithValue: (value, meta) => {
+                return new FulfillWithMeta(value, meta);
+              }
+            })).then((result) => {
+              if (result instanceof RejectWithValue) {
+                throw result;
+              }
+              if (result instanceof FulfillWithMeta) {
+                return fulfilled(result.payload, requestId, arg, result.meta);
+              }
+              return fulfilled(result, requestId, arg);
+            })]);
+          } catch (err) {
+            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
+          } finally {
+            if (abortHandler) {
+              abortController.signal.removeEventListener("abort", abortHandler);
+            }
+          }
+          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
+          if (!skipDispatch) {
+            dispatch(finalAction);
+          }
+          return finalAction;
+        }();
+        return Object.assign(promise, {
+          abort,
+          requestId,
+          arg,
+          unwrap() {
+            return promise.then(unwrapResult);
+          }
+        });
+      };
+    }
+    return Object.assign(actionCreator, {
+      pending,
+      rejected,
+      fulfilled,
+      settled: isAnyOf(rejected, fulfilled),
+      typePrefix
+    });
+  }
+  createAsyncThunk2.withTypes = () => createAsyncThunk2;
+  return createAsyncThunk2;
+})();
+function unwrapResult(action) {
+  if (action.meta && action.meta.rejectedWithValue) {
+    throw action.payload;
+  }
+  if (action.error) {
+    throw action.error;
+  }
+  return action.payload;
+}
+function isThenable(value) {
+  return value !== null && typeof value === "object" && typeof value.then === "function";
+}
+
+// src/createSlice.ts
+var asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
+var asyncThunkCreator = {
+  [asyncThunkSymbol]: createAsyncThunk
+};
+var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
+  ReducerType2["reducer"] = "reducer";
+  ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
+  ReducerType2["asyncThunk"] = "asyncThunk";
+  return ReducerType2;
+})(ReducerType || {});
+function getType(slice, actionKey) {
+  return `${slice}/${actionKey}`;
+}
+function buildCreateSlice({
+  creators
+} = {}) {
+  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];
+  return function createSlice2(options) {
+    const {
+      name,
+      reducerPath = name
+    } = options;
+    if (!name) {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
+    }
+    if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+      if (options.initialState === void 0) {
+        console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
+      }
+    }
+    const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
+    const reducerNames = Object.keys(reducers);
+    const context = {
+      sliceCaseReducersByName: {},
+      sliceCaseReducersByType: {},
+      actionCreators: {},
+      sliceMatchers: []
+    };
+    const contextMethods = {
+      addCase(typeOrActionCreator, reducer2) {
+        const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
+        if (!type) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
+        }
+        if (type in context.sliceCaseReducersByType) {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
+        }
+        context.sliceCaseReducersByType[type] = reducer2;
+        return contextMethods;
+      },
+      addMatcher(matcher, reducer2) {
+        context.sliceMatchers.push({
+          matcher,
+          reducer: reducer2
+        });
+        return contextMethods;
+      },
+      exposeAction(name2, actionCreator) {
+        context.actionCreators[name2] = actionCreator;
+        return contextMethods;
+      },
+      exposeCaseReducer(name2, reducer2) {
+        context.sliceCaseReducersByName[name2] = reducer2;
+        return contextMethods;
+      }
+    };
+    reducerNames.forEach((reducerName) => {
+      const reducerDefinition = reducers[reducerName];
+      const reducerDetails = {
+        reducerName,
+        type: getType(name, reducerName),
+        createNotation: typeof options.reducers === "function"
+      };
+      if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
+        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
+      } else {
+        handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
+      }
+    });
+    function buildReducer() {
+      if (process.env.NODE_ENV !== "production") {
+        if (typeof options.extraReducers === "object") {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
+        }
+      }
+      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
+      const finalCaseReducers = {
+        ...extraReducers,
+        ...context.sliceCaseReducersByType
+      };
+      return createReducer(options.initialState, (builder) => {
+        for (let key in finalCaseReducers) {
+          builder.addCase(key, finalCaseReducers[key]);
+        }
+        for (let sM of context.sliceMatchers) {
+          builder.addMatcher(sM.matcher, sM.reducer);
+        }
+        for (let m of actionMatchers) {
+          builder.addMatcher(m.matcher, m.reducer);
+        }
+        if (defaultCaseReducer) {
+          builder.addDefaultCase(defaultCaseReducer);
+        }
+      });
+    }
+    const selectSelf = (state) => state;
+    const injectedSelectorCache = /* @__PURE__ */ new Map();
+    const injectedStateCache = /* @__PURE__ */ new WeakMap();
+    let _reducer;
+    function reducer(state, action) {
+      if (!_reducer) _reducer = buildReducer();
+      return _reducer(state, action);
+    }
+    function getInitialState() {
+      if (!_reducer) _reducer = buildReducer();
+      return _reducer.getInitialState();
+    }
+    function makeSelectorProps(reducerPath2, injected = false) {
+      function selectSlice(state) {
+        let sliceState = state[reducerPath2];
+        if (typeof sliceState === "undefined") {
+          if (injected) {
+            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);
+          } else if (process.env.NODE_ENV !== "production") {
+            throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
+          }
+        }
+        return sliceState;
+      }
+      function getSelectors(selectState = selectSelf) {
+        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => /* @__PURE__ */ new WeakMap());
+        return getOrInsertComputed(selectorCache, selectState, () => {
+          const map = {};
+          for (const [name2, selector] of Object.entries(options.selectors ?? {})) {
+            map[name2] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);
+          }
+          return map;
+        });
+      }
+      return {
+        reducerPath: reducerPath2,
+        getSelectors,
+        get selectors() {
+          return getSelectors(selectSlice);
+        },
+        selectSlice
+      };
+    }
+    const slice = {
+      name,
+      reducer,
+      actions: context.actionCreators,
+      caseReducers: context.sliceCaseReducersByName,
+      getInitialState,
+      ...makeSelectorProps(reducerPath),
+      injectInto(injectable, {
+        reducerPath: pathOpt,
+        ...config
+      } = {}) {
+        const newReducerPath = pathOpt ?? reducerPath;
+        injectable.inject({
+          reducerPath: newReducerPath,
+          reducer
+        }, config);
+        return {
+          ...slice,
+          ...makeSelectorProps(newReducerPath, true)
+        };
+      }
+    };
+    return slice;
+  };
+}
+function wrapSelector(selector, selectState, getInitialState, injected) {
+  function wrapper(rootState, ...args) {
+    let sliceState = selectState(rootState);
+    if (typeof sliceState === "undefined") {
+      if (injected) {
+        sliceState = getInitialState();
+      } else if (process.env.NODE_ENV !== "production") {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
+      }
+    }
+    return selector(sliceState, ...args);
+  }
+  wrapper.unwrapped = selector;
+  return wrapper;
+}
+var createSlice = /* @__PURE__ */ buildCreateSlice();
+function buildReducerCreators() {
+  function asyncThunk(payloadCreator, config) {
+    return {
+      _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
+      payloadCreator,
+      ...config
+    };
+  }
+  asyncThunk.withTypes = () => asyncThunk;
+  return {
+    reducer(caseReducer) {
+      return Object.assign({
+        // hack so the wrapping function has the same name as the original
+        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
+        [caseReducer.name](...args) {
+          return caseReducer(...args);
+        }
+      }[caseReducer.name], {
+        _reducerDefinitionType: "reducer" /* reducer */
+      });
+    },
+    preparedReducer(prepare, reducer) {
+      return {
+        _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
+        prepare,
+        reducer
+      };
+    },
+    asyncThunk
+  };
+}
+function handleNormalReducerDefinition({
+  type,
+  reducerName,
+  createNotation
+}, maybeReducerWithPrepare, context) {
+  let caseReducer;
+  let prepareCallback;
+  if ("reducer" in maybeReducerWithPrepare) {
+    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
+    }
+    caseReducer = maybeReducerWithPrepare.reducer;
+    prepareCallback = maybeReducerWithPrepare.prepare;
+  } else {
+    caseReducer = maybeReducerWithPrepare;
+  }
+  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
+}
+function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
+  return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
+}
+function isCaseReducerWithPrepareDefinition(reducerDefinition) {
+  return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
+}
+function handleThunkCaseReducerDefinition({
+  type,
+  reducerName
+}, reducerDefinition, context, cAT) {
+  if (!cAT) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
+  }
+  const {
+    payloadCreator,
+    fulfilled,
+    pending,
+    rejected,
+    settled,
+    options
+  } = reducerDefinition;
+  const thunk = cAT(type, payloadCreator, options);
+  context.exposeAction(reducerName, thunk);
+  if (fulfilled) {
+    context.addCase(thunk.fulfilled, fulfilled);
+  }
+  if (pending) {
+    context.addCase(thunk.pending, pending);
+  }
+  if (rejected) {
+    context.addCase(thunk.rejected, rejected);
+  }
+  if (settled) {
+    context.addMatcher(thunk.settled, settled);
+  }
+  context.exposeCaseReducer(reducerName, {
+    fulfilled: fulfilled || noop,
+    pending: pending || noop,
+    rejected: rejected || noop,
+    settled: settled || noop
+  });
+}
+function noop() {
+}
+
+// src/entities/entity_state.ts
+function getInitialEntityState() {
+  return {
+    ids: [],
+    entities: {}
+  };
+}
+function createInitialStateFactory(stateAdapter) {
+  function getInitialState(additionalState = {}, entities) {
+    const state = Object.assign(getInitialEntityState(), additionalState);
+    return entities ? stateAdapter.setAll(state, entities) : state;
+  }
+  return {
+    getInitialState
+  };
+}
+
+// src/entities/state_selectors.ts
+function createSelectorsFactory() {
+  function getSelectors(selectState, options = {}) {
+    const {
+      createSelector: createSelector2 = createDraftSafeSelector
+    } = options;
+    const selectIds = (state) => state.ids;
+    const selectEntities = (state) => state.entities;
+    const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
+    const selectId = (_, id) => id;
+    const selectById = (entities, id) => entities[id];
+    const selectTotal = createSelector2(selectIds, (ids) => ids.length);
+    if (!selectState) {
+      return {
+        selectIds,
+        selectEntities,
+        selectAll,
+        selectTotal,
+        selectById: createSelector2(selectEntities, selectId, selectById)
+      };
+    }
+    const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
+    return {
+      selectIds: createSelector2(selectState, selectIds),
+      selectEntities: selectGlobalizedEntities,
+      selectAll: createSelector2(selectState, selectAll),
+      selectTotal: createSelector2(selectState, selectTotal),
+      selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
+    };
+  }
+  return {
+    getSelectors
+  };
+}
+
+// src/entities/state_adapter.ts
+var isDraftTyped = isDraft;
+function createSingleArgumentStateOperator(mutator) {
+  const operator = createStateOperator((_, state) => mutator(state));
+  return function operation(state) {
+    return operator(state, void 0);
+  };
+}
+function createStateOperator(mutator) {
+  return function operation(state, arg) {
+    function isPayloadActionArgument(arg2) {
+      return isFSA(arg2);
+    }
+    const runMutator = (draft) => {
+      if (isPayloadActionArgument(arg)) {
+        mutator(arg.payload, draft);
+      } else {
+        mutator(arg, draft);
+      }
+    };
+    if (isDraftTyped(state)) {
+      runMutator(state);
+      return state;
+    }
+    return produce(state, runMutator);
+  };
+}
+
+// src/entities/utils.ts
+function selectIdValue(entity, selectId) {
+  const key = selectId(entity);
+  if (process.env.NODE_ENV !== "production" && key === void 0) {
+    console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
+  }
+  return key;
+}
+function ensureEntitiesArray(entities) {
+  if (!Array.isArray(entities)) {
+    entities = Object.values(entities);
+  }
+  return entities;
+}
+function getCurrent(value) {
+  return isDraft(value) ? current(value) : value;
+}
+function splitAddedUpdatedEntities(newEntities, selectId, state) {
+  newEntities = ensureEntitiesArray(newEntities);
+  const existingIdsArray = getCurrent(state.ids);
+  const existingIds = new Set(existingIdsArray);
+  const added = [];
+  const addedIds = /* @__PURE__ */ new Set([]);
+  const updated = [];
+  for (const entity of newEntities) {
+    const id = selectIdValue(entity, selectId);
+    if (existingIds.has(id) || addedIds.has(id)) {
+      updated.push({
+        id,
+        changes: entity
+      });
+    } else {
+      addedIds.add(id);
+      added.push(entity);
+    }
+  }
+  return [added, updated, existingIdsArray];
+}
+
+// src/entities/unsorted_state_adapter.ts
+function createUnsortedStateAdapter(selectId) {
+  function addOneMutably(entity, state) {
+    const key = selectIdValue(entity, selectId);
+    if (key in state.entities) {
+      return;
+    }
+    state.ids.push(key);
+    state.entities[key] = entity;
+  }
+  function addManyMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    for (const entity of newEntities) {
+      addOneMutably(entity, state);
+    }
+  }
+  function setOneMutably(entity, state) {
+    const key = selectIdValue(entity, selectId);
+    if (!(key in state.entities)) {
+      state.ids.push(key);
+    }
+    ;
+    state.entities[key] = entity;
+  }
+  function setManyMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    for (const entity of newEntities) {
+      setOneMutably(entity, state);
+    }
+  }
+  function setAllMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    state.ids = [];
+    state.entities = {};
+    addManyMutably(newEntities, state);
+  }
+  function removeOneMutably(key, state) {
+    return removeManyMutably([key], state);
+  }
+  function removeManyMutably(keys, state) {
+    let didMutate = false;
+    keys.forEach((key) => {
+      if (key in state.entities) {
+        delete state.entities[key];
+        didMutate = true;
+      }
+    });
+    if (didMutate) {
+      state.ids = state.ids.filter((id) => id in state.entities);
+    }
+  }
+  function removeAllMutably(state) {
+    Object.assign(state, {
+      ids: [],
+      entities: {}
+    });
+  }
+  function takeNewKey(keys, update, state) {
+    const original3 = state.entities[update.id];
+    if (original3 === void 0) {
+      return false;
+    }
+    const updated = Object.assign({}, original3, update.changes);
+    const newKey = selectIdValue(updated, selectId);
+    const hasNewKey = newKey !== update.id;
+    if (hasNewKey) {
+      keys[update.id] = newKey;
+      delete state.entities[update.id];
+    }
+    ;
+    state.entities[newKey] = updated;
+    return hasNewKey;
+  }
+  function updateOneMutably(update, state) {
+    return updateManyMutably([update], state);
+  }
+  function updateManyMutably(updates, state) {
+    const newKeys = {};
+    const updatesPerEntity = {};
+    updates.forEach((update) => {
+      if (update.id in state.entities) {
+        updatesPerEntity[update.id] = {
+          id: update.id,
+          // Spreads ignore falsy values, so this works even if there isn't
+          // an existing update already at this key
+          changes: {
+            ...updatesPerEntity[update.id]?.changes,
+            ...update.changes
+          }
+        };
+      }
+    });
+    updates = Object.values(updatesPerEntity);
+    const didMutateEntities = updates.length > 0;
+    if (didMutateEntities) {
+      const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
+      if (didMutateIds) {
+        state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
+      }
+    }
+  }
+  function upsertOneMutably(entity, state) {
+    return upsertManyMutably([entity], state);
+  }
+  function upsertManyMutably(newEntities, state) {
+    const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
+    addManyMutably(added, state);
+    updateManyMutably(updated, state);
+  }
+  return {
+    removeAll: createSingleArgumentStateOperator(removeAllMutably),
+    addOne: createStateOperator(addOneMutably),
+    addMany: createStateOperator(addManyMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+    removeOne: createStateOperator(removeOneMutably),
+    removeMany: createStateOperator(removeManyMutably)
+  };
+}
+
+// src/entities/sorted_state_adapter.ts
+function findInsertIndex(sortedItems, item, comparisonFunction) {
+  let lowIndex = 0;
+  let highIndex = sortedItems.length;
+  while (lowIndex < highIndex) {
+    let middleIndex = lowIndex + highIndex >>> 1;
+    const currentItem = sortedItems[middleIndex];
+    const res = comparisonFunction(item, currentItem);
+    if (res >= 0) {
+      lowIndex = middleIndex + 1;
+    } else {
+      highIndex = middleIndex;
+    }
+  }
+  return lowIndex;
+}
+function insert(sortedItems, item, comparisonFunction) {
+  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
+  sortedItems.splice(insertAtIndex, 0, item);
+  return sortedItems;
+}
+function createSortedStateAdapter(selectId, comparer) {
+  const {
+    removeOne,
+    removeMany,
+    removeAll
+  } = createUnsortedStateAdapter(selectId);
+  function addOneMutably(entity, state) {
+    return addManyMutably([entity], state);
+  }
+  function addManyMutably(newEntities, state, existingIds) {
+    newEntities = ensureEntitiesArray(newEntities);
+    const existingKeys = new Set(existingIds ?? getCurrent(state.ids));
+    const addedKeys = /* @__PURE__ */ new Set();
+    const models = newEntities.filter((model) => {
+      const modelId = selectIdValue(model, selectId);
+      const notAdded = !addedKeys.has(modelId);
+      if (notAdded) addedKeys.add(modelId);
+      return !existingKeys.has(modelId) && notAdded;
+    });
+    if (models.length !== 0) {
+      mergeFunction(state, models);
+    }
+  }
+  function setOneMutably(entity, state) {
+    return setManyMutably([entity], state);
+  }
+  function setManyMutably(newEntities, state) {
+    let deduplicatedEntities = {};
+    newEntities = ensureEntitiesArray(newEntities);
+    if (newEntities.length !== 0) {
+      for (const item of newEntities) {
+        const entityId = selectId(item);
+        deduplicatedEntities[entityId] = item;
+        delete state.entities[entityId];
+      }
+      newEntities = ensureEntitiesArray(deduplicatedEntities);
+      mergeFunction(state, newEntities);
+    }
+  }
+  function setAllMutably(newEntities, state) {
+    newEntities = ensureEntitiesArray(newEntities);
+    state.entities = {};
+    state.ids = [];
+    addManyMutably(newEntities, state, []);
+  }
+  function updateOneMutably(update, state) {
+    return updateManyMutably([update], state);
+  }
+  function updateManyMutably(updates, state) {
+    let appliedUpdates = false;
+    let replacedIds = false;
+    for (let update of updates) {
+      const entity = state.entities[update.id];
+      if (!entity) {
+        continue;
+      }
+      appliedUpdates = true;
+      Object.assign(entity, update.changes);
+      const newId = selectId(entity);
+      if (update.id !== newId) {
+        replacedIds = true;
+        delete state.entities[update.id];
+        const oldIndex = state.ids.indexOf(update.id);
+        state.ids[oldIndex] = newId;
+        state.entities[newId] = entity;
+      }
+    }
+    if (appliedUpdates) {
+      mergeFunction(state, [], appliedUpdates, replacedIds);
+    }
+  }
+  function upsertOneMutably(entity, state) {
+    return upsertManyMutably([entity], state);
+  }
+  function upsertManyMutably(newEntities, state) {
+    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
+    if (added.length) {
+      addManyMutably(added, state, existingIdsArray);
+    }
+    if (updated.length) {
+      updateManyMutably(updated, state);
+    }
+  }
+  function areArraysEqual(a, b) {
+    if (a.length !== b.length) {
+      return false;
+    }
+    for (let i = 0; i < a.length; i++) {
+      if (a[i] === b[i]) {
+        continue;
+      }
+      return false;
+    }
+    return true;
+  }
+  const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {
+    const currentEntities = getCurrent(state.entities);
+    const currentIds = getCurrent(state.ids);
+    const stateEntities = state.entities;
+    let ids = currentIds;
+    if (replacedIds) {
+      ids = new Set(currentIds);
+    }
+    let sortedEntities = [];
+    for (const id of ids) {
+      const entity = currentEntities[id];
+      if (entity) {
+        sortedEntities.push(entity);
+      }
+    }
+    const wasPreviouslyEmpty = sortedEntities.length === 0;
+    for (const item of addedItems) {
+      stateEntities[selectId(item)] = item;
+      if (!wasPreviouslyEmpty) {
+        insert(sortedEntities, item, comparer);
+      }
+    }
+    if (wasPreviouslyEmpty) {
+      sortedEntities = addedItems.slice().sort(comparer);
+    } else if (appliedUpdates) {
+      sortedEntities.sort(comparer);
+    }
+    const newSortedIds = sortedEntities.map(selectId);
+    if (!areArraysEqual(currentIds, newSortedIds)) {
+      state.ids = newSortedIds;
+    }
+  };
+  return {
+    removeOne,
+    removeMany,
+    removeAll,
+    addOne: createStateOperator(addOneMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    addMany: createStateOperator(addManyMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertMany: createStateOperator(upsertManyMutably)
+  };
+}
+
+// src/entities/create_adapter.ts
+function createEntityAdapter(options = {}) {
+  const {
+    selectId,
+    sortComparer
+  } = {
+    sortComparer: false,
+    selectId: (instance) => instance.id,
+    ...options
+  };
+  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
+  const stateFactory = createInitialStateFactory(stateAdapter);
+  const selectorsFactory = createSelectorsFactory();
+  return {
+    selectId,
+    sortComparer,
+    ...stateFactory,
+    ...selectorsFactory,
+    ...stateAdapter
+  };
+}
+
+// src/listenerMiddleware/exceptions.ts
+var task = "task";
+var listener = "listener";
+var completed = "completed";
+var cancelled = "cancelled";
+var taskCancelled = `task-${cancelled}`;
+var taskCompleted = `task-${completed}`;
+var listenerCancelled = `${listener}-${cancelled}`;
+var listenerCompleted = `${listener}-${completed}`;
+var TaskAbortError = class {
+  constructor(code) {
+    this.code = code;
+    this.message = `${task} ${cancelled} (reason: ${code})`;
+  }
+  name = "TaskAbortError";
+  message;
+};
+
+// src/listenerMiddleware/utils.ts
+var assertFunction = (func, expected) => {
+  if (typeof func !== "function") {
+    throw new TypeError(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
+  }
+};
+var noop2 = () => {
+};
+var catchRejection = (promise, onError = noop2) => {
+  promise.catch(onError);
+  return promise;
+};
+var addAbortSignalListener = (abortSignal, callback) => {
+  abortSignal.addEventListener("abort", callback, {
+    once: true
+  });
+  return () => abortSignal.removeEventListener("abort", callback);
+};
+
+// src/listenerMiddleware/task.ts
+var validateActive = (signal) => {
+  if (signal.aborted) {
+    throw new TaskAbortError(signal.reason);
+  }
+};
+function raceWithSignal(signal, promise) {
+  let cleanup = noop2;
+  return new Promise((resolve, reject) => {
+    const notifyRejection = () => reject(new TaskAbortError(signal.reason));
+    if (signal.aborted) {
+      notifyRejection();
+      return;
+    }
+    cleanup = addAbortSignalListener(signal, notifyRejection);
+    promise.finally(() => cleanup()).then(resolve, reject);
+  }).finally(() => {
+    cleanup = noop2;
+  });
+}
+var runTask = async (task2, cleanUp) => {
+  try {
+    await Promise.resolve();
+    const value = await task2();
+    return {
+      status: "ok",
+      value
+    };
+  } catch (error) {
+    return {
+      status: error instanceof TaskAbortError ? "cancelled" : "rejected",
+      error
+    };
+  } finally {
+    cleanUp?.();
+  }
+};
+var createPause = (signal) => {
+  return (promise) => {
+    return catchRejection(raceWithSignal(signal, promise).then((output) => {
+      validateActive(signal);
+      return output;
+    }));
+  };
+};
+var createDelay = (signal) => {
+  const pause = createPause(signal);
+  return (timeoutMs) => {
+    return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
+  };
+};
+
+// src/listenerMiddleware/index.ts
+var {
+  assign
+} = Object;
+var INTERNAL_NIL_TOKEN = {};
+var alm = "listenerMiddleware";
+var createFork = (parentAbortSignal, parentBlockingPromises) => {
+  const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));
+  return (taskExecutor, opts) => {
+    assertFunction(taskExecutor, "taskExecutor");
+    const childAbortController = new AbortController();
+    linkControllers(childAbortController);
+    const result = runTask(async () => {
+      validateActive(parentAbortSignal);
+      validateActive(childAbortController.signal);
+      const result2 = await taskExecutor({
+        pause: createPause(childAbortController.signal),
+        delay: createDelay(childAbortController.signal),
+        signal: childAbortController.signal
+      });
+      validateActive(childAbortController.signal);
+      return result2;
+    }, () => childAbortController.abort(taskCompleted));
+    if (opts?.autoJoin) {
+      parentBlockingPromises.push(result.catch(noop2));
+    }
+    return {
+      result: createPause(parentAbortSignal)(result),
+      cancel() {
+        childAbortController.abort(taskCancelled);
+      }
+    };
+  };
+};
+var createTakePattern = (startListening, signal) => {
+  const take = async (predicate, timeout) => {
+    validateActive(signal);
+    let unsubscribe = () => {
+    };
+    const tuplePromise = new Promise((resolve, reject) => {
+      let stopListening = startListening({
+        predicate,
+        effect: (action, listenerApi) => {
+          listenerApi.unsubscribe();
+          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
+        }
+      });
+      unsubscribe = () => {
+        stopListening();
+        reject();
+      };
+    });
+    const promises = [tuplePromise];
+    if (timeout != null) {
+      promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
+    }
+    try {
+      const output = await raceWithSignal(signal, Promise.race(promises));
+      validateActive(signal);
+      return output;
+    } finally {
+      unsubscribe();
+    }
+  };
+  return (predicate, timeout) => catchRejection(take(predicate, timeout));
+};
+var getListenerEntryPropsFrom = (options) => {
+  let {
+    type,
+    actionCreator,
+    matcher,
+    predicate,
+    effect
+  } = options;
+  if (type) {
+    predicate = createAction(type).match;
+  } else if (actionCreator) {
+    type = actionCreator.type;
+    predicate = actionCreator.match;
+  } else if (matcher) {
+    predicate = matcher;
+  } else if (predicate) {
+  } else {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
+  }
+  assertFunction(effect, "options.listener");
+  return {
+    predicate,
+    type,
+    effect
+  };
+};
+var createListenerEntry = /* @__PURE__ */ assign((options) => {
+  const {
+    type,
+    predicate,
+    effect
+  } = getListenerEntryPropsFrom(options);
+  const entry = {
+    id: nanoid(),
+    effect,
+    type,
+    predicate,
+    pending: /* @__PURE__ */ new Set(),
+    unsubscribe: () => {
+      throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
+    }
+  };
+  return entry;
+}, {
+  withTypes: () => createListenerEntry
+});
+var findListenerEntry = (listenerMap, options) => {
+  const {
+    type,
+    effect,
+    predicate
+  } = getListenerEntryPropsFrom(options);
+  return Array.from(listenerMap.values()).find((entry) => {
+    const matchPredicateOrType = typeof type === "string" ? entry.type === type : entry.predicate === predicate;
+    return matchPredicateOrType && entry.effect === effect;
+  });
+};
+var cancelActiveListeners = (entry) => {
+  entry.pending.forEach((controller) => {
+    controller.abort(listenerCancelled);
+  });
+};
+var createClearListenerMiddleware = (listenerMap, executingListeners) => {
+  return () => {
+    for (const listener2 of executingListeners.keys()) {
+      cancelActiveListeners(listener2);
+    }
+    listenerMap.clear();
+  };
+};
+var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
+  try {
+    errorHandler(errorToNotify, errorInfo);
+  } catch (errorHandlerError) {
+    setTimeout(() => {
+      throw errorHandlerError;
+    }, 0);
+  }
+};
+var addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), {
+  withTypes: () => addListener
+});
+var clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
+var removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), {
+  withTypes: () => removeListener
+});
+var defaultErrorHandler = (...args) => {
+  console.error(`${alm}/error`, ...args);
+};
+var createListenerMiddleware = (middlewareOptions = {}) => {
+  const listenerMap = /* @__PURE__ */ new Map();
+  const executingListeners = /* @__PURE__ */ new Map();
+  const trackExecutingListener = (entry) => {
+    const count = executingListeners.get(entry) ?? 0;
+    executingListeners.set(entry, count + 1);
+  };
+  const untrackExecutingListener = (entry) => {
+    const count = executingListeners.get(entry) ?? 1;
+    if (count === 1) {
+      executingListeners.delete(entry);
+    } else {
+      executingListeners.set(entry, count - 1);
+    }
+  };
+  const {
+    extra,
+    onError = defaultErrorHandler
+  } = middlewareOptions;
+  assertFunction(onError, "onError");
+  const insertEntry = (entry) => {
+    entry.unsubscribe = () => listenerMap.delete(entry.id);
+    listenerMap.set(entry.id, entry);
+    return (cancelOptions) => {
+      entry.unsubscribe();
+      if (cancelOptions?.cancelActive) {
+        cancelActiveListeners(entry);
+      }
+    };
+  };
+  const startListening = (options) => {
+    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options);
+    return insertEntry(entry);
+  };
+  assign(startListening, {
+    withTypes: () => startListening
+  });
+  const stopListening = (options) => {
+    const entry = findListenerEntry(listenerMap, options);
+    if (entry) {
+      entry.unsubscribe();
+      if (options.cancelActive) {
+        cancelActiveListeners(entry);
+      }
+    }
+    return !!entry;
+  };
+  assign(stopListening, {
+    withTypes: () => stopListening
+  });
+  const notifyListener = async (entry, action, api, getOriginalState) => {
+    const internalTaskController = new AbortController();
+    const take = createTakePattern(startListening, internalTaskController.signal);
+    const autoJoinPromises = [];
+    try {
+      entry.pending.add(internalTaskController);
+      trackExecutingListener(entry);
+      await Promise.resolve(entry.effect(
+        action,
+        // Use assign() rather than ... to avoid extra helper functions added to bundle
+        assign({}, api, {
+          getOriginalState,
+          condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
+          take,
+          delay: createDelay(internalTaskController.signal),
+          pause: createPause(internalTaskController.signal),
+          extra,
+          signal: internalTaskController.signal,
+          fork: createFork(internalTaskController.signal, autoJoinPromises),
+          unsubscribe: entry.unsubscribe,
+          subscribe: () => {
+            listenerMap.set(entry.id, entry);
+          },
+          cancelActiveListeners: () => {
+            entry.pending.forEach((controller, _, set) => {
+              if (controller !== internalTaskController) {
+                controller.abort(listenerCancelled);
+                set.delete(controller);
+              }
+            });
+          },
+          cancel: () => {
+            internalTaskController.abort(listenerCancelled);
+            entry.pending.delete(internalTaskController);
+          },
+          throwIfCancelled: () => {
+            validateActive(internalTaskController.signal);
+          }
+        })
+      ));
+    } catch (listenerError) {
+      if (!(listenerError instanceof TaskAbortError)) {
+        safelyNotifyError(onError, listenerError, {
+          raisedBy: "effect"
+        });
+      }
+    } finally {
+      await Promise.all(autoJoinPromises);
+      internalTaskController.abort(listenerCompleted);
+      untrackExecutingListener(entry);
+      entry.pending.delete(internalTaskController);
+    }
+  };
+  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);
+  const middleware = (api) => (next) => (action) => {
+    if (!isAction(action)) {
+      return next(action);
+    }
+    if (addListener.match(action)) {
+      return startListening(action.payload);
+    }
+    if (clearAllListeners.match(action)) {
+      clearListenerMiddleware();
+      return;
+    }
+    if (removeListener.match(action)) {
+      return stopListening(action.payload);
+    }
+    let originalState = api.getState();
+    const getOriginalState = () => {
+      if (originalState === INTERNAL_NIL_TOKEN) {
+        throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
+      }
+      return originalState;
+    };
+    let result;
+    try {
+      result = next(action);
+      if (listenerMap.size > 0) {
+        const currentState = api.getState();
+        const listenerEntries = Array.from(listenerMap.values());
+        for (const entry of listenerEntries) {
+          let runListener = false;
+          try {
+            runListener = entry.predicate(action, currentState, originalState);
+          } catch (predicateError) {
+            runListener = false;
+            safelyNotifyError(onError, predicateError, {
+              raisedBy: "predicate"
+            });
+          }
+          if (!runListener) {
+            continue;
+          }
+          notifyListener(entry, action, api, getOriginalState);
+        }
+      }
+    } finally {
+      originalState = INTERNAL_NIL_TOKEN;
+    }
+    return result;
+  };
+  return {
+    middleware,
+    startListening,
+    stopListening,
+    clearListeners: clearListenerMiddleware
+  };
+};
+
+// src/dynamicMiddleware/index.ts
+var createMiddlewareEntry = (middleware) => ({
+  middleware,
+  applied: /* @__PURE__ */ new Map()
+});
+var matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;
+var createDynamicMiddleware = () => {
+  const instanceId = nanoid();
+  const middlewareMap = /* @__PURE__ */ new Map();
+  const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
+    payload: middlewares,
+    meta: {
+      instanceId
+    }
+  })), {
+    withTypes: () => withMiddleware
+  });
+  const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
+    middlewares.forEach((middleware2) => {
+      getOrInsertComputed(middlewareMap, middleware2, createMiddlewareEntry);
+    });
+  }, {
+    withTypes: () => addMiddleware
+  });
+  const getFinalMiddleware = (api) => {
+    const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => getOrInsertComputed(entry.applied, api, entry.middleware));
+    return compose(...appliedMiddleware);
+  };
+  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
+  const middleware = (api) => (next) => (action) => {
+    if (isWithMiddleware(action)) {
+      addMiddleware(...action.payload);
+      return api.dispatch;
+    }
+    return getFinalMiddleware(api)(next)(action);
+  };
+  return {
+    middleware,
+    addMiddleware,
+    withMiddleware,
+    instanceId
+  };
+};
+
+// src/combineSlices.ts
+import { combineReducers as combineReducers2 } from "redux";
+var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
+var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
+var ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
+var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
+var stateProxyMap = /* @__PURE__ */ new WeakMap();
+var createStateProxy = (state, reducerMap, initialStateCache) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {
+  get: (target, prop, receiver) => {
+    if (prop === ORIGINAL_STATE) return target;
+    const result = Reflect.get(target, prop, receiver);
+    if (typeof result === "undefined") {
+      const cached = initialStateCache[prop];
+      if (typeof cached !== "undefined") return cached;
+      const reducer = reducerMap[prop];
+      if (reducer) {
+        const reducerResult = reducer(void 0, {
+          type: nanoid()
+        });
+        if (typeof reducerResult === "undefined") {
+          throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
+        }
+        initialStateCache[prop] = reducerResult;
+        return reducerResult;
+      }
+    }
+    return result;
+  }
+}));
+var original = (state) => {
+  if (!isStateProxy(state)) {
+    throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
+  }
+  return state[ORIGINAL_STATE];
+};
+var emptyObject = {};
+var noopReducer = (state = emptyObject) => state;
+function combineSlices(...slices) {
+  const reducerMap = Object.fromEntries(getReducers(slices));
+  const getReducer = () => Object.keys(reducerMap).length ? combineReducers2(reducerMap) : noopReducer;
+  let reducer = getReducer();
+  function combinedReducer(state, action) {
+    return reducer(state, action);
+  }
+  combinedReducer.withLazyLoadedSlices = () => combinedReducer;
+  const initialStateCache = {};
+  const inject = (slice, config = {}) => {
+    const {
+      reducerPath,
+      reducer: reducerToInject
+    } = slice;
+    const currentReducer = reducerMap[reducerPath];
+    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
+      if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
+        console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
+      }
+      return combinedReducer;
+    }
+    if (config.overrideExisting && currentReducer !== reducerToInject) {
+      delete initialStateCache[reducerPath];
+    }
+    reducerMap[reducerPath] = reducerToInject;
+    reducer = getReducer();
+    return combinedReducer;
+  };
+  const selector = Object.assign(function makeSelector(selectorFn, selectState) {
+    return function selector2(state, ...args) {
+      return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap, initialStateCache), ...args);
+    };
+  }, {
+    original
+  });
+  return Object.assign(combinedReducer, {
+    inject,
+    selector
+  });
+}
+
+// src/formatProdErrorMessage.ts
+function formatProdErrorMessage(code) {
+  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
+}
+export {
+  ReducerType,
+  SHOULD_AUTOBATCH,
+  TaskAbortError,
+  Tuple,
+  addListener,
+  asyncThunkCreator,
+  autoBatchEnhancer,
+  buildCreateSlice,
+  clearAllListeners,
+  combineSlices,
+  configureStore,
+  createAction,
+  createActionCreatorInvariantMiddleware,
+  createAsyncThunk,
+  createDraftSafeSelector,
+  createDraftSafeSelectorCreator,
+  createDynamicMiddleware,
+  createEntityAdapter,
+  createImmutableStateInvariantMiddleware,
+  createListenerMiddleware,
+  produce as createNextState,
+  createReducer,
+  createSelector,
+  createSelectorCreator,
+  createSerializableStateInvariantMiddleware,
+  createSlice,
+  current,
+  findNonSerializableValue,
+  formatProdErrorMessage,
+  freeze,
+  isActionCreator,
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isDraft,
+  isFSA as isFluxStandardAction,
+  isFulfilled,
+  isImmutableDefault,
+  isPending,
+  isPlain,
+  isRejected,
+  isRejectedWithValue,
+  lruMemoize,
+  miniSerializeError,
+  nanoid,
+  original2 as original,
+  prepareAutoBatched,
+  removeListener,
+  unwrapResult,
+  weakMapMemoize
+};
+//# sourceMappingURL=redux-toolkit.modern.mjs.map
Index: node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../src/index.ts","../src/immerImports.ts","../src/reselectImports.ts","../src/createDraftSafeSelector.ts","../src/reduxImports.ts","../src/devtoolsExtension.ts","../src/getDefaultMiddleware.ts","../src/tsHelpers.ts","../src/createAction.ts","../src/actionCreatorInvariantMiddleware.ts","../src/utils.ts","../src/immutableStateInvariantMiddleware.ts","../src/serializableStateInvariantMiddleware.ts","../src/autoBatchEnhancer.ts","../src/getDefaultEnhancers.ts","../src/configureStore.ts","../src/mapBuilders.ts","../src/createReducer.ts","../src/matchers.ts","../src/nanoid.ts","../src/createAsyncThunk.ts","../src/createSlice.ts","../src/entities/entity_state.ts","../src/entities/state_selectors.ts","../src/entities/state_adapter.ts","../src/entities/utils.ts","../src/entities/unsorted_state_adapter.ts","../src/entities/sorted_state_adapter.ts","../src/entities/create_adapter.ts","../src/listenerMiddleware/exceptions.ts","../src/listenerMiddleware/utils.ts","../src/listenerMiddleware/task.ts","../src/listenerMiddleware/index.ts","../src/dynamicMiddleware/index.ts","../src/combineSlices.ts","../src/formatProdErrorMessage.ts"],"sourcesContent":["// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage';\nexport * from 'redux';\nexport { freeze, original } from 'immer';\nexport { createNextState, current, isDraft } from './immerImports';\nexport type { Draft, WritableDraft } from 'immer';\nexport { createSelector, lruMemoize } from 'reselect';\nexport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport type { Selector, OutputSelector } from 'reselect';\nexport { createDraftSafeSelector, createDraftSafeSelectorCreator } from './createDraftSafeSelector';\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';\nexport {\n// js\nconfigureStore } from './configureStore';\nexport type {\n// types\nConfigureStoreOptions, EnhancedStore } from './configureStore';\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension';\nexport {\n// js\ncreateAction, isActionCreator, isFSA as isFluxStandardAction } from './createAction';\nexport type {\n// types\nPayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction } from './createAction';\nexport {\n// js\ncreateReducer } from './createReducer';\nexport type {\n// types\nActions, CaseReducer, CaseReducers } from './createReducer';\nexport {\n// js\ncreateSlice, buildCreateSlice, asyncThunkCreator, ReducerType } from './createSlice';\nexport type {\n// types\nCreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, ReducerCreators, SliceSelectors } from './createSlice';\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nexport {\n// js\ncreateImmutableStateInvariantMiddleware, isImmutableDefault } from './immutableStateInvariantMiddleware';\nexport type {\n// types\nImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\nexport {\n// js\ncreateSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nSerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nexport type {\n// types\nActionReducerMapBuilder, AsyncThunkReducers } from './mapBuilders';\nexport { Tuple } from './utils';\nexport { createEntityAdapter } from './entities/create_adapter';\nexport type { EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer } from './entities/models';\nexport { createAsyncThunk, unwrapResult, miniSerializeError } from './createAsyncThunk';\nexport type { AsyncThunk, AsyncThunkConfig, AsyncThunkDispatchConfig, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, GetState, GetThunkAPI, SerializedError, CreateAsyncThunkFunction } from './createAsyncThunk';\nexport {\n// js\nisAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue } from './matchers';\nexport type {\n// types\nActionMatchingAllOf, ActionMatchingAnyOf } from './matchers';\nexport { nanoid } from './nanoid';\nexport type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult } from './listenerMiddleware/index';\nexport type { AnyListenerPredicate } from './listenerMiddleware/types';\nexport { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError } from './listenerMiddleware/index';\nexport type { AddMiddleware, DynamicDispatch, DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './dynamicMiddleware/types';\nexport { createDynamicMiddleware } from './dynamicMiddleware/index';\nexport { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer } from './autoBatchEnhancer';\nexport type { AutoBatchOptions } from './autoBatchEnhancer';\nexport { combineSlices } from './combineSlices';\nexport type { CombinedSliceReducer, WithSlice, WithSlicePreloadedState } from './combineSlices';\nexport type { ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, SafePromise } from './tsHelpers';\nexport { formatProdErrorMessage } from './formatProdErrorMessage';","export { current, isDraft, produce as createNextState, isDraftable, setUseStrictIteration } from 'immer';","export { createSelectorCreator, weakMapMemoize } from 'reselect';","import { current, isDraft } from './immerImports';\nimport { createSelectorCreator, weakMapMemoize } from './reselectImports';\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (...args: unknown[]) => {\n  const createSelector = (createSelectorCreator as any)(...args);\n  const createDraftSafeSelector = Object.assign((...args: unknown[]) => {\n    const selector = createSelector(...args);\n    const wrappedSelector = (value: unknown, ...rest: unknown[]) => selector(isDraft(value) ? current(value) : value, ...rest);\n    Object.assign(wrappedSelector, selector);\n    return wrappedSelector as any;\n  }, {\n    withTypes: () => createDraftSafeSelector\n  });\n  return createDraftSafeSelector;\n};\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector = /* @__PURE__ */\ncreateDraftSafeSelectorCreator(weakMapMemoize);","export { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from 'redux';","import type { Action, ActionCreator, StoreEnhancer } from 'redux';\nimport { compose } from './reduxImports';\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string;\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | {\n    [key: string]: ActionCreator<any>;\n  };\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number;\n  /**\n   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\n   *\n   * @default 50\n   */\n  maxAge?: number;\n  /**\n   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?: boolean | {\n    /**\n     * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n     * - `false` - will handle also circular references.\n     * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n     * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n     *   For each of them you can indicate if to include (by setting as `true`).\n     *   For `function` key you can also specify a custom function which handles serialization.\n     *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n     */\n    options?: undefined | boolean | {\n      date?: true;\n      regex?: true;\n      undefined?: true;\n      error?: true;\n      symbol?: true;\n      map?: true;\n      set?: true;\n      function?: true | ((fn: (...args: any[]) => any) => string);\n    };\n    /**\n     * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\n     * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n     * key. So you can deserialize it back while importing or persisting data.\n     * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\n     */\n    replacer?: (key: string, value: unknown) => any;\n    /**\n     * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n     * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n     * as an example on how to serialize special data types and get them back.\n     */\n    reviver?: (key: string, value: unknown) => any;\n    /**\n     * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n     * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n     * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n     */\n    immutable?: any;\n    /**\n     * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n     */\n    refs?: any;\n  };\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A;\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S;\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[];\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[];\n  /**\n   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean;\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean;\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string;\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean;\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean;\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean;\n  /**\n   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean;\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean;\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean;\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean;\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom';\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom';\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean;\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean;\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean;\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean;\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean;\n  };\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string);\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number;\n}\ntype Compose = typeof compose;\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose;\n  <StoreExt extends {}>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\n  if (arguments.length === 0) return undefined;\n  if (typeof arguments[0] === 'object') return compose;\n  return compose.apply(null, arguments as any as Function[]);\n};\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>;\n} = typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION__ : function () {\n  return function (noop) {\n    return noop;\n  };\n};","import type { Middleware, UnknownAction } from 'redux';\nimport type { ThunkMiddleware } from 'redux-thunk';\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk';\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware';\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware';\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware';\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware';\nimport type { ExcludeFromTuple } from './tsHelpers';\nimport { Tuple } from './utils';\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean';\n}\ninterface ThunkOptions<E = any> {\n  extraArgument: E;\n}\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions;\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;\n}\nexport type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {\n  thunk: false;\n} ? never : O extends {\n  thunk: {\n    extraArgument: infer E;\n  };\n} ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;\nexport type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {\n  thunk: true;\n  immutableCheck: true;\n  serializableCheck: true;\n  actionCreatorCheck: true;\n}>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;\nexport const buildGetDefaultMiddleware = <S = any,>(): GetDefaultMiddleware<S> => function getDefaultMiddleware(options) {\n  const {\n    thunk = true,\n    immutableCheck = true,\n    serializableCheck = true,\n    actionCreatorCheck = true\n  } = options ?? {};\n  let middlewareArray = new Tuple<Middleware[]>();\n  if (thunk) {\n    if (isBoolean(thunk)) {\n      middlewareArray.push(thunkMiddleware);\n    } else {\n      middlewareArray.push(withExtraArgument(thunk.extraArgument));\n    }\n  }\n  if (process.env.NODE_ENV !== 'production') {\n    if (immutableCheck) {\n      /* PROD_START_REMOVE_UMD */\n      let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(immutableCheck)) {\n        immutableOptions = immutableCheck;\n      }\n      middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n      /* PROD_STOP_REMOVE_UMD */\n    }\n    if (serializableCheck) {\n      let serializableOptions: SerializableStateInvariantMiddlewareOptions = {};\n      if (!isBoolean(serializableCheck)) {\n        serializableOptions = serializableCheck;\n      }\n      middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n    }\n    if (actionCreatorCheck) {\n      let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {};\n      if (!isBoolean(actionCreatorCheck)) {\n        actionCreatorOptions = actionCreatorCheck;\n      }\n      middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n    }\n  }\n  return middlewareArray as any;\n};","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n  Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n  (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport { isAction } from './reduxImports';\nimport type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<P = void, T extends string = string, M = never, E = never> = {\n  payload: P;\n  type: T;\n} & ([M] extends [never] ? {} : {\n  meta: M;\n}) & ([E] extends [never] ? {} : {\n  error: E;\n});\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> = ((...args: any[]) => {\n  payload: P;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  error: any;\n}) | ((...args: any[]) => {\n  payload: P;\n  meta: any;\n  error: any;\n});\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {\n  error: infer E;\n} ? E : never, ReturnType<PA> extends {\n  meta: infer M;\n} ? M : never> : void;\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T;\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>;\n};\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>;\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>;\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>;\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>;\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>,\n// else\nIsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>,\n// else\nIfVoid<P, ActionCreatorWithoutPayload<T>,\n// else\nIfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>,\n// else\nActionCreatorWithPayload<P, T>>>>>>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args);\n      if (!prepared) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(0) : 'prepareAction did not return an object');\n      }\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && {\n          meta: prepared.meta\n        }),\n        ...('error' in prepared && {\n          error: prepared.error\n        })\n      };\n    }\n    return {\n      type,\n      payload: args[0]\n    };\n  }\n  actionCreator.toString = () => `${type}`;\n  actionCreator.type = type;\n  actionCreator.match = (action: unknown): action is PayloadAction => isAction(action) && action.type === type;\n  return actionCreator;\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function {\n  return typeof action === 'function' && 'type' in action &&\n  // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n  hasMatchFunction(action as any);\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string;\n  payload?: unknown;\n  error?: unknown;\n  meta?: unknown;\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1;\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends ((...args: any[]) => any) ? True : False;","import type { Middleware } from 'redux';\nimport { isActionCreator as isRTKAction } from './createAction';\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & {\n    type?: unknown;\n  };\n}\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : [];\n  const actionName = splitType[splitType.length - 1] || 'actionCreator';\n  return `Detected an action creator with type \"${type || 'unknown'}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nexport function createActionCreatorInvariantMiddleware(options: ActionCreatorInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  }\n  const {\n    isActionCreator = isRTKAction\n  } = options;\n  return () => next => action => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type));\n    }\n    return next(action);\n  };\n}","import { createNextState, isDraftable } from './immerImports';\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0;\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now();\n      try {\n        return fn();\n      } finally {\n        const finished = Date.now();\n        elapsed += finished - started;\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n      }\n    }\n  };\n}\nexport function delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {\n  constructor(length: number);\n  constructor(...items: Items);\n  constructor(...items: any[]) {\n    super(...items);\n    Object.setPrototypeOf(this, Tuple.prototype);\n  }\n  static override get [Symbol.species]() {\n    return Tuple as any;\n  }\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr);\n  }\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this));\n    }\n    return new Tuple(...arr.concat(this));\n  }\n}\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val;\n}\nexport function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, value).get(key) as V;\n}\nexport function getOrInsertComputed<K extends object, V>(map: WeakMap<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K, V>(map: Map<K, V>, key: K, compute: (key: K) => V): V;\nexport function getOrInsertComputed<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, compute: (key: K) => V): V {\n  if (map.has(key)) return map.get(key) as V;\n  return map.set(key, compute(key)).get(key) as V;\n}\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | PromiseLike<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve: any;\n  let reject: any;\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return {\n    promise,\n    resolve,\n    reject\n  };\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { Middleware } from 'redux';\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware';\nimport { getTimeMeasureUtils } from './utils';\ntype EntryProcessor = (key: string, value: any) => any;\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value);\n}\nexport function trackForMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths | undefined, obj: any) {\n  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);\n    }\n  };\n}\ninterface TrackedProperty {\n  value: any;\n  children: Record<string, any>;\n}\nfunction trackProperties(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], obj: Record<string, any>, path: string = '', checkedObjects: Set<Record<string, any>> = new Set()) {\n  const tracked: Partial<TrackedProperty> = {\n    value: obj\n  };\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj);\n    tracked.children = {};\n    const hasIgnoredPaths = ignoredPaths.length > 0;\n    for (const key in obj) {\n      const nestedPath = path ? path + '.' + key : key;\n      if (hasIgnoredPaths) {\n        const hasMatches = ignoredPaths.some(ignored => {\n          if (ignored instanceof RegExp) {\n            return ignored.test(nestedPath);\n          }\n          return nestedPath === ignored;\n        });\n        if (hasMatches) {\n          continue;\n        }\n      }\n      tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);\n    }\n  }\n  return tracked as TrackedProperty;\n}\nfunction detectMutations(isImmutable: IsImmutableFunc, ignoredPaths: IgnorePaths = [], trackedProperty: TrackedProperty, obj: any, sameParentRef: boolean = false, path: string = ''): {\n  wasMutated: boolean;\n  path?: string;\n} {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined;\n  const sameRef = prevObj === obj;\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return {\n      wasMutated: true,\n      path\n    };\n  }\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return {\n      wasMutated: false\n    };\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {};\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true;\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true;\n  }\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n    if (result.wasMutated) {\n      return result;\n    }\n  }\n  return {\n    wasMutated: false\n  };\n}\ntype IsImmutableFunc = (value: any) => boolean;\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc;\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths;\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number;\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(options: ImmutableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    function stringify(obj: any, serializer?: EntryProcessor, indent?: string | number, decycler?: EntryProcessor): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\n    }\n    function getSerialize(serializer?: EntryProcessor, decycler?: EntryProcessor): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = [];\n      if (!decycler) decycler = function (_: string, value: any) {\n        if (stack[0] === value) return '[Circular ~]';\n        return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';\n      };\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this);\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value);\n        } else stack.push(value);\n        return serializer == null ? value : serializer.call(this, key, value);\n      };\n    }\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32\n    } = options;\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n    return ({\n      getState\n    }) => {\n      let state = getState();\n      let tracker = track(state);\n      let result;\n      return next => action => {\n        const measureUtils = getTimeMeasureUtils(warnAfter, 'ImmutableStateInvariantMiddleware');\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ''}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        const dispatchedAction = next(action);\n        measureUtils.measureTime(() => {\n          state = getState();\n          result = tracker.detectMutations();\n          // Track before potentially not meeting the invariant\n          tracker = track(state);\n          if (result.wasMutated) {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ''}. Take a look at the reducer(s) handling the action ${stringify(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n        return dispatchedAction;\n      };\n    };\n  }\n}","import type { Middleware } from 'redux';\nimport { isAction, isPlainObject } from './reduxImports';\nimport { getTimeMeasureUtils } from './utils';\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val;\n  return val == null || type === 'string' || type === 'boolean' || type === 'number' || Array.isArray(val) || isPlainObject(val);\n}\ninterface NonSerializableValue {\n  keyPath: string;\n  value: unknown;\n}\nexport type IgnorePaths = readonly (string | RegExp)[];\n\n/**\n * @public\n */\nexport function findNonSerializableValue(value: unknown, path: string = '', isSerializable: (value: unknown) => boolean = isPlain, getEntries?: (value: unknown) => [string, any][], ignoredPaths: IgnorePaths = [], cache?: WeakSet<object>): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false;\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value\n    };\n  }\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  if (cache?.has(value)) return false;\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n  const hasIgnoredPaths = ignoredPaths.length > 0;\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key;\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some(ignored => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath);\n        }\n        return nestedPath === ignored;\n      });\n      if (hasMatches) {\n        continue;\n      }\n    }\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue\n      };\n    }\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n      if (foundNestedSerializable) {\n        return foundNestedSerializable;\n      }\n    }\n  }\n  if (cache && isNestedFrozen(value)) cache.add(value);\n  return false;\n}\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false;\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue;\n    if (!isNestedFrozen(nestedValue)) return false;\n  }\n  return true;\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean;\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][];\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[];\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[];\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number;\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean;\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean;\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean;\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(options: SerializableStateInvariantMiddlewareOptions = {}): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => next => action => next(action);\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false\n    } = options;\n    const cache: WeakSet<object> | undefined = !disableCache && WeakSet ? new WeakSet() : undefined;\n    return storeAPI => next => action => {\n      if (!isAction(action)) {\n        return next(action);\n      }\n      const result = next(action);\n      const measureUtils = getTimeMeasureUtils(warnAfter, 'SerializableStateInvariantMiddleware');\n      if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type as any) !== -1)) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(action, '', isSerializable, getEntries, ignoredActionPaths, cache);\n          if (foundActionNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundActionNonSerializableValue;\n            console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, '\\nTake a look at the logic that dispatched this action: ', action, '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)', '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)');\n          }\n        });\n      }\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState();\n          const foundStateNonSerializableValue = findNonSerializableValue(state, '', isSerializable, getEntries, ignoredPaths, cache);\n          if (foundStateNonSerializableValue) {\n            const {\n              keyPath,\n              value\n            } = foundStateNonSerializableValue;\n            console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n          }\n        });\n        measureUtils.warnIfExceeded();\n      }\n      return result;\n    };\n  }\n}","import type { StoreEnhancer } from 'redux';\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch';\nexport const prepareAutoBatched = <T,>() => (payload: T): {\n  payload: T;\n  meta: unknown;\n} => ({\n  payload,\n  meta: {\n    [SHOULD_AUTOBATCH]: true\n  }\n});\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout);\n  };\n};\nexport type AutoBatchOptions = {\n  type: 'tick';\n} | {\n  type: 'timer';\n  timeout: number;\n} | {\n  type: 'raf';\n} | {\n  type: 'callback';\n  queueNotification: (notify: () => void) => void;\n};\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer = (options: AutoBatchOptions = {\n  type: 'raf'\n}): StoreEnhancer => next => (...args) => {\n  const store = next(...args);\n  let notifying = true;\n  let shouldNotifyAtEndOfTick = false;\n  let notificationQueued = false;\n  const listeners = new Set<() => void>();\n  const queueCallback = options.type === 'tick' ? queueMicrotask : options.type === 'raf' ?\n  // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n  typeof window !== 'undefined' && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === 'callback' ? options.queueNotification : createQueueWithTimer(options.timeout);\n  const notifyListeners = () => {\n    // We're running at the end of the event loop tick.\n    // Run the real listener callbacks to actually update the UI.\n    notificationQueued = false;\n    if (shouldNotifyAtEndOfTick) {\n      shouldNotifyAtEndOfTick = false;\n      listeners.forEach(l => l());\n    }\n  };\n  return Object.assign({}, store, {\n    // Override the base `store.subscribe` method to keep original listeners\n    // from running if we're delaying notifications\n    subscribe(listener: () => void) {\n      // Each wrapped listener will only call the real listener if\n      // the `notifying` flag is currently active when it's called.\n      // This lets the base store work as normal, while the actual UI\n      // update becomes controlled by this enhancer.\n      const wrappedListener: typeof listener = () => notifying && listener();\n      const unsubscribe = store.subscribe(wrappedListener);\n      listeners.add(listener);\n      return () => {\n        unsubscribe();\n        listeners.delete(listener);\n      };\n    },\n    // Override the base `store.dispatch` method so that we can check actions\n    // for the `shouldAutoBatch` flag and determine if batching is active\n    dispatch(action: any) {\n      try {\n        // If the action does _not_ have the `shouldAutoBatch` flag,\n        // we resume/continue normal notify-after-each-dispatch behavior\n        notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n        // If a `notifyListeners` microtask was queued, you can't cancel it.\n        // Instead, we set a flag so that it's a no-op when it does run\n        shouldNotifyAtEndOfTick = !notifying;\n        if (shouldNotifyAtEndOfTick) {\n          // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n          // a microtask to notify listeners at the end of the event loop tick.\n          // Make sure we only enqueue this _once_ per tick.\n          if (!notificationQueued) {\n            notificationQueued = true;\n            queueCallback(notifyListeners);\n          }\n        }\n        // Go ahead and process the action as usual, including reducers.\n        // If normal notification behavior is enabled, the store will notify\n        // all of its own listeners, and the wrapper callbacks above will\n        // see `notifying` is true and pass on to the real listener callbacks.\n        // If we're \"batching\" behavior, then the wrapped callbacks will\n        // bail out, causing the base store notification behavior to be no-ops.\n        return store.dispatch(action);\n      } finally {\n        // Assume we're back to normal behavior after each action\n        notifying = true;\n      }\n    }\n  });\n};","import type { StoreEnhancer } from 'redux';\nimport type { AutoBatchOptions } from './autoBatchEnhancer';\nimport { autoBatchEnhancer } from './autoBatchEnhancer';\nimport { Tuple } from './utils';\nimport type { Middlewares } from './configureStore';\nimport type { ExtractDispatchExtensions } from './tsHelpers';\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions;\n};\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>]>;\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>,>(middlewareEnhancer: StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>): GetDefaultEnhancers<M> => function getDefaultEnhancers(options) {\n  const {\n    autoBatch = true\n  } = options ?? {};\n  let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer);\n  if (autoBatch) {\n    enhancerArray.push(autoBatchEnhancer(typeof autoBatch === 'object' ? autoBatch : undefined));\n  }\n  return enhancerArray as any;\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Reducer, ReducersMapObject, Middleware, Action, StoreEnhancer, Store, UnknownAction } from 'redux';\nimport { applyMiddleware, createStore, compose, combineReducers, isPlainObject } from './reduxImports';\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';\nimport { composeWithDevTools } from './devtoolsExtension';\nimport type { ThunkMiddlewareFor, GetDefaultMiddleware } from './getDefaultMiddleware';\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware';\nimport type { ExtractDispatchExtensions, ExtractStoreExtensions, ExtractStateExtensions, UnknownIfNonSpecific } from './tsHelpers';\nimport type { Tuple } from './utils';\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers';\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers';\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions;\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean;\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P;\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;\n}\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;\ntype Enhancers = ReadonlyArray<StoreEnhancer>;\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[StoreEnhancer<{\n  dispatch: ExtractDispatchExtensions<M>;\n}>, StoreEnhancer]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>();\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined\n  } = options || {};\n  let rootReducer: Reducer<S, A, P>;\n  if (typeof reducer === 'function') {\n    rootReducer = reducer;\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>;\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(1) : '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\n  }\n  if (process.env.NODE_ENV !== 'production' && middleware && typeof middleware !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(2) : '`middleware` field must be a callback');\n  }\n  let finalMiddleware: Tuple<Middlewares<S>>;\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware);\n    if (process.env.NODE_ENV !== 'production' && !Array.isArray(finalMiddleware)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(3) : 'when using a middleware builder function, an array of middleware must be returned');\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware();\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(4) : 'each middleware provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>();\n    finalMiddleware.forEach(middleware => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(42) : 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.');\n      }\n      middlewareReferences.add(middleware);\n    });\n  }\n  let finalCompose = compose;\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools)\n    });\n  }\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer);\n  if (process.env.NODE_ENV !== 'production' && enhancers && typeof enhancers !== 'function') {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(5) : '`enhancers` field must be a callback');\n  }\n  let storeEnhancers = typeof enhancers === 'function' ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(6) : '`enhancers` callback must return an array');\n  }\n  if (process.env.NODE_ENV !== 'production' && storeEnhancers.some((item: any) => typeof item !== 'function')) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(7) : 'each enhancer provided to configureStore must be a function');\n  }\n  if (process.env.NODE_ENV !== 'production' && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n    console.error('middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`');\n  }\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers);\n  return createStore(rootReducer, preloadedState as P, composedEnhancer);\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7 } from \"@reduxjs/toolkit\";\nimport type { Action } from 'redux';\nimport type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';\nimport type { TypeGuard } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk';\nexport type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;\n  rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;\n  fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;\n  settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;\n};\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>;\n  type: Type;\n};\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;\n\n  /**\n   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.\n   * @remarks\n   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param asyncThunk - The async thunk action creator itself.\n   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.\n   * @example\n  ```ts no-transpile\n  import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'\n  const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {\n  const response = await fetch(`https://reqres.in/api/users/${id}`)\n  return (await response.json()).data\n  })\n  const reducer = createReducer(initialState, (builder) => {\n  builder.addAsyncThunk(fetchUserById, {\n    pending: (state, action) => {\n      state.fetchUserById.loading = 'pending'\n    },\n    fulfilled: (state, action) => {\n      state.fetchUserById.data = action.payload\n    },\n    rejected: (state, action) => {\n      state.fetchUserById.error = action.error\n    },\n    settled: (state, action) => {\n      state.fetchUserById.loading = action.meta.requestStatus\n    },\n  })\n  })\n   */\n  addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n  ```ts\n  import {\n  createAction,\n  createReducer,\n  AsyncThunk,\n  UnknownAction,\n  } from \"@reduxjs/toolkit\";\n  type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n  type PendingAction = ReturnType<GenericAsyncThunk[\"pending\"]>;\n  type RejectedAction = ReturnType<GenericAsyncThunk[\"rejected\"]>;\n  type FulfilledAction = ReturnType<GenericAsyncThunk[\"fulfilled\"]>;\n  const initialState: Record<string, string> = {};\n  const resetAction = createAction(\"reset-tracked-loading-state\");\n  function isPendingAction(action: UnknownAction): action is PendingAction {\n  return typeof action.type === \"string\" && action.type.endsWith(\"/pending\");\n  }\n  const reducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(resetAction, () => initialState)\n    // matcher can be defined outside as a type predicate function\n    .addMatcher(isPendingAction, (state, action) => {\n      state[action.meta.requestId] = \"pending\";\n    })\n    .addMatcher(\n      // matcher can be defined inline as a type predicate function\n      (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"rejected\";\n      }\n    )\n    // matcher can just return boolean and the matcher can receive a generic argument\n    .addMatcher<FulfilledAction>(\n      (action) => action.type.endsWith(\"/fulfilled\"),\n      (state, action) => {\n        state[action.meta.requestId] = \"fulfilled\";\n      }\n    );\n  });\n  ```\n   */\n  addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n  ```ts\n  import { createReducer } from '@reduxjs/toolkit'\n  const initialState = { otherActions: 0 }\n  const reducer = createReducer(initialState, builder => {\n  builder\n    // .addCase(...)\n    // .addMatcher(...)\n    .addDefaultCase((state, action) => {\n      state.otherActions++\n    })\n  })\n  ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {};\n}\nexport function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [CaseReducers<S, any>, ActionMatcherDescriptionCollection<S>, CaseReducer<S, Action> | undefined] {\n  const actionsMap: CaseReducers<S, any> = {};\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = [];\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined;\n  const builder = {\n    addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<S>) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(26) : '`builder.addCase` should only be called before calling `builder.addMatcher`');\n        }\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(27) : '`builder.addCase` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n      if (!type) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(28) : '`builder.addCase` cannot be called with an empty action type');\n      }\n      if (type in actionsMap) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(29) : '`builder.addCase` cannot be called with two reducers for the same action type ' + `'${type}'`);\n      }\n      actionsMap[type] = reducer;\n      return builder;\n    },\n    addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>) {\n      if (process.env.NODE_ENV !== 'production') {\n        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(43) : '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;\n      if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;\n      if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;\n      if (reducers.settled) actionMatchers.push({\n        matcher: asyncThunk.settled,\n        reducer: reducers.settled\n      });\n      return builder;\n    },\n    addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<S, A extends Action ? A : A & Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(30) : '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`');\n        }\n      }\n      actionMatchers.push({\n        matcher,\n        reducer\n      });\n      return builder;\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(31) : '`builder.addDefaultCase` can only be called once');\n        }\n      }\n      defaultCaseReducer = reducer;\n      return builder;\n    }\n  };\n  builderCallback(builder);\n  return [actionsMap, actionMatchers, defaultCaseReducer];\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { Draft } from 'immer';\nimport { createNextState, isDraft, isDraftable, setUseStrictIteration } from './immerImports';\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { ActionReducerMapBuilder } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { NoInfer, TypeGuard } from './tsHelpers';\nimport { freezeDraftable } from './utils';\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>;\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>;\n  reducer: CaseReducer<S, NoInfer<A>>;\n};\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;\nexport type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void };\nexport type NotFunction<T> = T extends Function ? never : T;\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function';\n}\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S;\n};\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n```ts\nimport {\n  createAction,\n  createReducer,\n  UnknownAction,\n  PayloadAction,\n} from \"@reduxjs/toolkit\";\n\nconst increment = createAction<number>(\"increment\");\nconst decrement = createAction<number>(\"decrement\");\n\nfunction isActionWithNumberPayload(\n  action: UnknownAction\n): action is PayloadAction<number> {\n  return typeof action.payload === \"number\";\n}\n\nconst reducer = createReducer(\n  {\n    counter: 0,\n    sumOfNumberPayloads: 0,\n    unhandledActions: 0,\n  },\n  (builder) => {\n    builder\n      .addCase(increment, (state, action) => {\n        // action is inferred correctly here\n        state.counter += action.payload;\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {\n        state.counter -= action.payload;\n      })\n      // You can apply a \"matcher function\" to incoming actions\n      .addMatcher(isActionWithNumberPayload, (state, action) => {})\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {});\n  }\n);\n```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n    }\n  }\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S;\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState());\n  } else {\n    const frozenInitialState = freezeDraftable(initialState);\n    getInitialState = () => frozenInitialState;\n  }\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n      matcher\n    }) => matcher(action)).map(({\n      reducer\n    }) => reducer)];\n    if (caseReducers.filter(cr => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer];\n    }\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S>; // We can assume this is already a draft\n          const result = caseReducer(draft, action);\n          if (result === undefined) {\n            return previousState;\n          }\n          return result as S;\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action);\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState;\n            }\n            throw Error('A case reducer on a non-draftable value must not return undefined');\n          }\n          return result as S;\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action);\n          });\n        }\n      }\n      return previousState;\n    }, state);\n  }\n  reducer.getInitialState = getInitialState;\n  return reducer as ReducerWithInitialState<S>;\n}","import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';\nimport { hasMatchFunction } from './tsHelpers';\nimport type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action);\n  } else {\n    return matcher(action);\n  }\n};\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every(matcher => matches(matcher, action));\n  };\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]) {\n  if (!action || !action.meta) return false;\n  const hasValidRequestId = typeof action.meta.requestId === 'string';\n  const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n  return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return typeof a[0] === 'function' && 'pending' in a[0] && 'fulfilled' in a[0] && 'rejected' in a[0];\n}\nexport type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction;\nexport function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.pending));\n}\nexport type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.rejected));\n}\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {\n  rejectValue: infer RejectedValue;\n}> ? {\n  payload: RejectedValue;\n} : unknown);\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;\nexport function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue;\n  };\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0]);\n  }\n  return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;\nexport function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.map(asyncThunk => asyncThunk.fulfilled));\n}\nexport type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;\nexport type AnyAsyncThunk = {\n  pending: {\n    match: (action: any) => action is any;\n  };\n  fulfilled: {\n    match: (action: any) => action is any;\n  };\n  rejected: {\n    match: (action: any) => action is any;\n  };\n};\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;\nexport function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected']);\n  }\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0]);\n  }\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}","// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\n/**\n *\n * @public\n */\nexport let nanoid = (size = 21) => {\n  let id = '';\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size;\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[Math.random() * 64 | 0];\n  }\n  return id;\n};","import type { Dispatch, UnknownAction } from 'redux';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport type { ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport { isAnyOf } from './matchers';\nimport { nanoid } from './nanoid';\nimport type { FallbackIfUnknown, Id, IsAny, IsUnknown, SafePromise } from './tsHelpers';\nexport type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {\n  dispatch: D;\n  getState: () => S;\n  extra: E;\n  requestId: string;\n  signal: AbortSignal;\n  abort: (reason?: string) => void;\n  rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;\n  fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;\n};\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string;\n  message?: string;\n  stack?: string;\n  code?: string;\n}\nconst commonProperties: Array<keyof SerializedError> = ['name', 'message', 'stack', 'code'];\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue';\n  constructor(public readonly payload: Payload, public readonly meta: RejectedMeta) {}\n}\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta';\n  constructor(public readonly payload: Payload, public readonly meta: FulfilledMeta) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {};\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property];\n      }\n    }\n    return simpleError;\n  }\n  return {\n    message: String(value)\n  };\n};\nexport type AsyncThunkConfig = {\n  state?: unknown;\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;\n  extra?: unknown;\n  rejectValue?: unknown;\n  serializedErrorType?: unknown;\n  pendingMeta?: unknown;\n  fulfilledMeta?: unknown;\n  rejectedMeta?: unknown;\n};\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State;\n} ? State : unknown;\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends {\n  extra: infer Extra;\n} ? Extra : unknown;\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch;\n} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue;\n} ? RejectValue : unknown;\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta;\n} ? PendingMeta : unknown;\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta;\n} ? FulfilledMeta : unknown;\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta;\n} ? RejectedMeta : unknown;\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType;\n} ? GetSerializedErrorType : SerializedError;\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {\n  abort: (reason?: string) => void;\n  requestId: string;\n  arg: ThunkArg;\n  unwrap: () => Promise<Returned>;\n};\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal;\n}\ntype AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg,\n// any handling\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// unknown handling\nunknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n: [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n: [void] extends [ThunkArg] // make optional\n? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n: [undefined] extends [ThunkArg] ? WithStrictNullChecks<\n// with strict nullChecks: make optional\n(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n// without strict null checks this will match everything, so don't make it optional\n(arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> // default case: normal argument\n: (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean;\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string;\n} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   *\n   * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n   * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n   */\n  getPendingMeta?(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}, {\n  /**\n   * A method to generate additional properties to be added to `meta` of the pending action.\n   */\n  getPendingMeta(base: {\n    arg: ThunkArg;\n    requestId: string;\n  }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;\n}>;\nexport type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?], undefined, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'pending';\n} & GetPendingMeta<ThunkApiConfig>>;\nexport type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Error | null, string, ThunkArg, GetRejectValue<ThunkApiConfig>?, GetRejectedMeta<ThunkApiConfig>?], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'rejected';\n  aborted: boolean;\n  condition: boolean;\n} & (({\n  rejectedWithValue: false;\n} & { [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined }) | ({\n  rejectedWithValue: true;\n} & GetRejectedMeta<ThunkApiConfig>))>;\nexport type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?], Returned, string, never, {\n  arg: ThunkArg;\n  requestId: string;\n  requestStatus: 'fulfilled';\n} & GetFulfilledMeta<ThunkApiConfig>>;\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;\n  fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;\n  // matchSettled?\n  settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;\n  typePrefix: string;\n};\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;\nexport type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n  withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n};\nconst externalAbortMessage = 'External signal was aborted';\nexport const createAsyncThunk = /* @__PURE__ */(() => {\n  function createAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>;\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>;\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>;\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>;\n    const fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/fulfilled', (payload: Returned, requestId: string, arg: ThunkArg, meta?: FulfilledMeta) => ({\n      payload,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'fulfilled' as const\n      }\n    }));\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/pending', (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n      payload: undefined,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        requestStatus: 'pending' as const\n      }\n    }));\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> = createAction(typePrefix + '/rejected', (error: Error | null, requestId: string, arg: ThunkArg, payload?: RejectedValue, meta?: RejectedMeta) => ({\n      payload,\n      error: (options && options.serializeError || miniSerializeError)(error || 'Rejected') as GetSerializedErrorType<ThunkApiConfig>,\n      meta: {\n        ...(meta as any || {}),\n        arg,\n        requestId,\n        rejectedWithValue: !!payload,\n        requestStatus: 'rejected' as const,\n        aborted: error?.name === 'AbortError',\n        condition: error?.name === 'ConditionError'\n      }\n    }));\n    function actionCreator(arg: ThunkArg, {\n      signal\n    }: AsyncThunkDispatchConfig = {}): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n        const abortController = new AbortController();\n        let abortHandler: (() => void) | undefined;\n        let abortReason: string | undefined;\n        function abort(reason?: string) {\n          abortReason = reason;\n          abortController.abort();\n        }\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage);\n          } else {\n            signal.addEventListener('abort', () => abort(externalAbortMessage), {\n              once: true\n            });\n          }\n        }\n        const promise = async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>;\n          try {\n            let conditionResult = options?.condition?.(arg, {\n              getState,\n              extra\n            });\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult;\n            }\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.'\n              };\n            }\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted'\n                });\n              };\n              abortController.signal.addEventListener('abort', abortHandler, {\n                once: true\n              });\n            });\n            dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n              requestId,\n              arg\n            }, {\n              getState,\n              extra\n            })) as any);\n            finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n              dispatch,\n              getState,\n              extra,\n              requestId,\n              signal: abortController.signal,\n              abort,\n              rejectWithValue: ((value: RejectedValue, meta?: RejectedMeta) => {\n                return new RejectWithValue(value, meta);\n              }) as any,\n              fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                return new FulfillWithMeta(value, meta);\n              }) as any\n            })).then(result => {\n              if (result instanceof RejectWithValue) {\n                throw result;\n              }\n              if (result instanceof FulfillWithMeta) {\n                return fulfilled(result.payload, requestId, arg, result.meta);\n              }\n              return fulfilled(result as any, requestId, arg);\n            })]);\n          } catch (err) {\n            finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err as any, requestId, arg);\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler);\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && (finalAction as any).meta.condition;\n          if (!skipDispatch) {\n            dispatch(finalAction as any);\n          }\n          return finalAction;\n        }();\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult);\n          }\n        });\n      };\n    }\n    return Object.assign(actionCreator as AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig>, {\n      pending,\n      rejected,\n      fulfilled,\n      settled: isAnyOf(rejected, fulfilled),\n      typePrefix\n    });\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk;\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>;\n})();\ninterface UnwrappableAction {\n  payload: any;\n  meta?: any;\n  error?: any;\n}\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {\n  error: any;\n}>['payload'];\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload;\n  }\n  if (action.error) {\n    throw action.error;\n  }\n  return action.payload;\n}\ntype WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return value !== null && typeof value === 'object' && typeof value.then === 'function';\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3, formatProdErrorMessage as _formatProdErrorMessage4, formatProdErrorMessage as _formatProdErrorMessage5, formatProdErrorMessage as _formatProdErrorMessage6, formatProdErrorMessage as _formatProdErrorMessage7, formatProdErrorMessage as _formatProdErrorMessage8 } from \"@reduxjs/toolkit\";\nimport type { Action, Reducer, UnknownAction } from 'redux';\nimport type { Selector } from 'reselect';\nimport type { InjectConfig } from './combineSlices';\nimport type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';\nimport { createAction } from './createAction';\nimport type { AsyncThunk, AsyncThunkConfig, AsyncThunkOptions, AsyncThunkPayloadCreator, OverrideThunkApiConfigs } from './createAsyncThunk';\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk';\nimport type { ActionMatcherDescriptionCollection, CaseReducer, ReducerWithInitialState } from './createReducer';\nimport { createReducer } from './createReducer';\nimport type { ActionReducerMapBuilder, AsyncThunkReducers, TypedActionCreator } from './mapBuilders';\nimport { executeReducerBuilderCallback } from './mapBuilders';\nimport type { Id, TypeGuard } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\nconst asyncThunkSymbol = /* @__PURE__ */Symbol.for('rtk-slice-createasyncthunk');\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk;\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk\n};\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath;\n};\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice name.\n   */\n  name: Name;\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath;\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>;\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>;\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>;\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State;\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>>;\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {\n    inject: (slice: {\n      reducerPath: string;\n      reducer: Reducer;\n    }, config?: InjectConfig) => void;\n  }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State;\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]?: State | undefined }>>;\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State;\n};\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name;\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath;\n\n  /**\n   * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n   */\n  initialState: State | (() => State);\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n  ```ts\n  import { createAction, createSlice, Action } from '@reduxjs/toolkit'\n  const incrementBy = createAction<number>('incrementBy')\n  const decrement = createAction('decrement')\n  interface RejectedAction extends Action {\n  error: Error\n  }\n  function isRejectedAction(action: Action): action is RejectedAction {\n  return action.type.endsWith('rejected')\n  }\n  createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {},\n  extraReducers: builder => {\n    builder\n      .addCase(incrementBy, (state, action) => {\n        // action is inferred correctly here if using TS\n      })\n      // You can chain calls, or have separate `builder.addCase()` lines each time\n      .addCase(decrement, (state, action) => {})\n      // You can match a range of action types\n      .addMatcher(\n        isRejectedAction,\n        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n        (state, action) => {}\n      )\n      // and provide a default case if no other handlers matched\n      .addDefaultCase((state, action) => {})\n    }\n  })\n  ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors;\n}\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T;\n};\nexport type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>;\n  prepare: PrepareAction<Action['payload']>;\n};\nexport interface CaseReducerWithPrepareDefinition<State, Action extends PayloadAction> extends CaseReducerWithPrepare<State, Action>, ReducerDefinition<ReducerType.reducerWithPrepare> {}\ntype AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;\n};\ntype AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;\n};\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = { [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K] };\ninterface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {\n  <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;\n  <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;\n  withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;\n}\nexport interface ReducerCreators<State> {\n  reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;\n  reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;\n  asyncThunk: AsyncThunkCreator<State>;\n  preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare;\n    prepare: Prepare;\n    reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;\n  };\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any;\n};\ntype SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {\n  prepare: any;\n} ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {\n  reducer: any;\n} ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never };\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<CR extends {\n  prepare: any;\n}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ((state: any, action: infer Action) => any) ? Action extends {\n  payload: infer P;\n} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {\n  reducer: infer Reducer;\n} ? Reducer : Definition : never };\ntype RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {\n  unwrapped: S;\n} : never;\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = { [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState> };\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends {\n  reducer(s: S, action?: infer A): any;\n} ? {\n  prepare(...a: never[]): Omit<A, 'type'>;\n} : {} };\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`;\n}\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator;\n  };\n}\nexport function buildCreateSlice({\n  creators\n}: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n  return function createSlice<State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {\n    const {\n      name,\n      reducerPath = name as unknown as ReducerPath\n    } = options;\n    if (!name) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(11) : '`name` is a required option for createSlice');\n    }\n    if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n      if (options.initialState === undefined) {\n        console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`');\n      }\n    }\n    const reducers = (typeof options.reducers === 'function' ? options.reducers(buildReducerCreators<State>()) : options.reducers) || {};\n    const reducerNames = Object.keys(reducers);\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: []\n    };\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(typeOrActionCreator: string | TypedActionCreator<any>, reducer: CaseReducer<State>) {\n        const type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type;\n        if (!type) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(12) : '`context.addCase` cannot be called with an empty action type');\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(13) : '`context.addCase` cannot be called with two reducers for the same action type: ' + type);\n        }\n        context.sliceCaseReducersByType[type] = reducer;\n        return contextMethods;\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({\n          matcher,\n          reducer\n        });\n        return contextMethods;\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator;\n        return contextMethods;\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer;\n        return contextMethods;\n      }\n    };\n    reducerNames.forEach(reducerName => {\n      const reducerDefinition = reducers[reducerName];\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function'\n      };\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n      } else {\n        handleNormalReducerDefinition<State>(reducerDetails, reducerDefinition as any, contextMethods);\n      }\n    });\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage4(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n        }\n      }\n      const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = undefined] = typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType\n      };\n      return createReducer(options.initialState, builder => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>);\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer);\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer);\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer);\n        }\n      });\n    }\n    const selectSelf = (state: State) => state;\n    const injectedSelectorCache = new Map<boolean, WeakMap<(rootState: any) => State | undefined, Record<string, (rootState: any) => any>>>();\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>();\n    let _reducer: ReducerWithInitialState<State>;\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer(state, action);\n    }\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer();\n      return _reducer.getInitialState();\n    }\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(reducerPath: CurrentReducerPath, injected = false): Pick<Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, 'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'> {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath];\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage5(15) : 'selectSlice returned undefined for an uninjected slice reducer');\n          }\n        }\n        return sliceState;\n      }\n      function getSelectors(selectState: (rootState: any) => State = selectSelf) {\n        const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => new WeakMap());\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {};\n          for (const [name, selector] of Object.entries(options.selectors ?? {})) {\n            map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);\n          }\n          return map;\n        }) as any;\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice);\n        },\n        selectSlice\n      };\n    }\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, {\n        reducerPath: pathOpt,\n        ...config\n      } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath;\n        injectable.inject({\n          reducerPath: newReducerPath,\n          reducer\n        }, config);\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true)\n        } as any;\n      }\n    };\n    return slice;\n  };\n}\nfunction wrapSelector<State, NewState, S extends Selector<State>>(selector: S, selectState: Selector<NewState, State>, getInitialState: () => State, injected?: boolean) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState);\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState();\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage6(16) : 'selectState returned undefined for an uninjected slice reducer');\n      }\n    }\n    return selector(sliceState, ...args);\n  }\n  wrapper.unwrapped = selector;\n  return wrapper as RemappedSelector<S, NewState>;\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */buildCreateSlice();\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<string, CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>>;\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>;\n  sliceMatchers: ActionMatcherDescriptionCollection<State>;\n  actionCreators: Record<string, Function>;\n}\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ReducerHandlingContextMethods<State>;\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ReducerHandlingContextMethods<State>;\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(matcher: TypeGuard<A>, reducer: CaseReducer<State, A extends Action ? A : A & Action>): ReducerHandlingContextMethods<State>;\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * context.exposeAction(\"addPost\", createAction<Post>(\"addPost\"));\n   *\n   * export const { addPost } = slice.actions\n   *\n   * dispatch(addPost(post))\n   */\n  exposeAction(name: string, actionCreator: Function): ReducerHandlingContextMethods<State>;\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * context.exposeCaseReducer(\"addPost\", (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload)\n   * })\n   *\n   * slice.caseReducers.addPost([], addPost(post))\n   */\n  exposeCaseReducer(name: string, reducer: CaseReducer<State, any> | Pick<AsyncThunkSliceReducerDefinition<State, any, any, any>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>): ReducerHandlingContextMethods<State>;\n}\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string;\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string;\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean;\n}\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(payloadCreator: AsyncThunkPayloadCreator<any, any>, config: AsyncThunkSliceReducerConfig<State, any>): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config\n    };\n  }\n  asyncThunk.withTypes = () => asyncThunk;\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign({\n        // hack so the wrapping function has the same name as the original\n        // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n        [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n          return caseReducer(...args);\n        }\n      }[caseReducer.name], {\n        _reducerDefinitionType: ReducerType.reducer\n      } as const);\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer\n      };\n    },\n    asyncThunk: asyncThunk as any\n  };\n}\nfunction handleNormalReducerDefinition<State>({\n  type,\n  reducerName,\n  createNotation\n}: ReducerDetails, maybeReducerWithPrepare: CaseReducer<State, {\n  payload: any;\n  type: string;\n}> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, context: ReducerHandlingContextMethods<State>) {\n  let caseReducer: CaseReducer<State, any>;\n  let prepareCallback: PrepareAction<any> | undefined;\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage7(17) : 'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.');\n    }\n    caseReducer = maybeReducerWithPrepare.reducer;\n    prepareCallback = maybeReducerWithPrepare.prepare;\n  } else {\n    caseReducer = maybeReducerWithPrepare;\n  }\n  context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition<State>(reducerDefinition: any): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk;\n}\nfunction isCaseReducerWithPrepareDefinition<State>(reducerDefinition: any): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare;\n}\nfunction handleThunkCaseReducerDefinition<State>({\n  type,\n  reducerName\n}: ReducerDetails, reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, context: ReducerHandlingContextMethods<State>, cAT: typeof _createAsyncThunk | undefined) {\n  if (!cAT) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage8(18) : 'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + 'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.');\n  }\n  const {\n    payloadCreator,\n    fulfilled,\n    pending,\n    rejected,\n    settled,\n    options\n  } = reducerDefinition;\n  const thunk = cAT(type, payloadCreator, options as any);\n  context.exposeAction(reducerName, thunk);\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled);\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending);\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected);\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled);\n  }\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop\n  });\n}\nfunction noop() {}","import type { EntityId, EntityState, EntityStateAdapter, EntityStateFactory } from './models';\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<T, Id> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>\n  };\n}\nexport function createInitialStateFactory<T, Id extends EntityId>(stateAdapter: EntityStateAdapter<T, Id>): EntityStateFactory<T, Id> {\n  function getInitialState(state?: undefined, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id>;\n  function getInitialState<S extends object>(additionalState: S, entities?: readonly T[] | Record<Id, T>): EntityState<T, Id> & S;\n  function getInitialState(additionalState: any = {}, entities?: readonly T[] | Record<Id, T>): any {\n    const state = Object.assign(getInitialEntityState(), additionalState);\n    return entities ? stateAdapter.setAll(state, entities) : state;\n  }\n  return {\n    getInitialState\n  };\n}","import type { CreateSelectorFunction, Selector } from 'reselect';\nimport { createDraftSafeSelector } from '../createDraftSafeSelector';\nimport type { EntityId, EntitySelectors, EntityState } from './models';\ntype AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction;\n};\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;\n  function getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;\n  function getSelectors<V>(selectState?: (state: V) => EntityState<T, Id>, options: GetSelectorsOptions = {}): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction\n    } = options;\n    const selectIds = (state: EntityState<T, Id>) => state.ids;\n    const selectEntities = (state: EntityState<T, Id>) => state.entities;\n    const selectAll = createSelector(selectIds, selectEntities, (ids, entities): T[] => ids.map(id => entities[id]!));\n    const selectId = (_: unknown, id: Id) => id;\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id];\n    const selectTotal = createSelector(selectIds, ids => ids.length);\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById)\n      };\n    }\n    const selectGlobalizedEntities = createSelector(selectState as Selector<V, EntityState<T, Id>>, selectEntities);\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(selectGlobalizedEntities, selectId, selectById)\n    };\n  }\n  return {\n    getSelectors\n  };\n}","import { createNextState, isDraft } from '../immerImports';\nimport type { Draft } from 'immer';\nimport type { EntityId, DraftableEntityState, PreventAny } from './models';\nimport type { PayloadAction } from '../createAction';\nimport { isFSA } from '../createAction';\nexport const isDraftTyped = isDraft as <T>(value: T | Draft<T>) => value is Draft<T>;\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(mutator: (state: DraftableEntityState<T, Id>) => void) {\n  const operator = createStateOperator((_: undefined, state: DraftableEntityState<T, Id>) => mutator(state));\n  return function operation<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S {\n    return operator(state as S, undefined);\n  };\n}\nexport function createStateOperator<T, Id extends EntityId, R>(mutator: (arg: R, state: DraftableEntityState<T, Id>) => void) {\n  return function operation<S extends DraftableEntityState<T, Id>>(state: S, arg: R | PayloadAction<R>): S {\n    function isPayloadActionArgument(arg: R | PayloadAction<R>): arg is PayloadAction<R> {\n      return isFSA(arg);\n    }\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft);\n      } else {\n        mutator(arg, draft);\n      }\n    };\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state);\n\n      // since it's a draft, we'll just return it\n      return state;\n    }\n    return createNextState(state, runMutator);\n  };\n}","import type { Draft } from 'immer';\nimport { current, isDraft } from '../immerImports';\nimport type { DraftableEntityState, EntityId, IdSelector, Update } from './models';\nexport function selectIdValue<T, Id extends EntityId>(entity: T, selectId: IdSelector<T, Id>) {\n  const key = selectId(entity);\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    console.warn('The entity passed to the `selectId` implementation returned undefined.', 'You should probably provide your own `selectId` implementation.', 'The entity that was passed:', entity, 'The `selectId` implementation:', selectId.toString());\n  }\n  return key;\n}\nexport function ensureEntitiesArray<T, Id extends EntityId>(entities: readonly T[] | Record<Id, T>): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities);\n  }\n  return entities;\n}\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T;\n}\nexport function splitAddedUpdatedEntities<T, Id extends EntityId>(newEntities: readonly T[] | Record<Id, T>, selectId: IdSelector<T, Id>, state: DraftableEntityState<T, Id>): [T[], Update<T, Id>[], Id[]] {\n  newEntities = ensureEntitiesArray(newEntities);\n  const existingIdsArray = getCurrent(state.ids);\n  const existingIds = new Set<Id>(existingIdsArray);\n  const added: T[] = [];\n  const addedIds = new Set<Id>([]);\n  const updated: Update<T, Id>[] = [];\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId);\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({\n        id,\n        changes: entity\n      });\n    } else {\n      addedIds.add(id);\n      added.push(entity);\n    }\n  }\n  return [added, updated, existingIdsArray];\n}","import type { Draft } from 'immer';\nimport type { EntityStateAdapter, IdSelector, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator, createSingleArgumentStateOperator } from './state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities } from './utils';\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (key in state.entities) {\n      return;\n    }\n    state.ids.push(key as Id & Draft<Id>);\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      addOneMutably(entity, state);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId);\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>);\n    }\n    ;\n    (state.entities as Record<Id, T>)[key] = entity;\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    for (const entity of newEntities) {\n      setOneMutably(entity, state);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.ids = [];\n    state.entities = {} as Record<Id, T>;\n    addManyMutably(newEntities, state);\n  }\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state);\n  }\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false;\n    keys.forEach(key => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key];\n        didMutate = true;\n      }\n    });\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter(id => id in state.entities) as Id[] | Draft<Id[]>;\n    }\n  }\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {}\n    });\n  }\n  function takeNewKey(keys: {\n    [id: string]: Id;\n  }, update: Update<T, Id>, state: R): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id];\n    if (original === undefined) {\n      return false;\n    }\n    const updated: T = Object.assign({}, original, update.changes);\n    const newKey = selectIdValue(updated, selectId);\n    const hasNewKey = newKey !== update.id;\n    if (hasNewKey) {\n      keys[update.id] = newKey;\n      delete (state.entities as Record<Id, T>)[update.id];\n    }\n    ;\n    (state.entities as Record<Id, T>)[newKey] = updated;\n    return hasNewKey;\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    const newKeys: {\n      [id: string]: Id;\n    } = {};\n    const updatesPerEntity: {\n      [id: string]: Update<T, Id>;\n    } = {};\n    updates.forEach(update => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes\n          }\n        };\n      }\n    });\n    updates = Object.values(updatesPerEntity);\n    const didMutateEntities = updates.length > 0;\n    if (didMutateEntities) {\n      const didMutateIds = updates.filter(update => takeNewKey(newKeys, update, state)).length > 0;\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map(e => selectIdValue(e as T, selectId));\n      }\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    addManyMutably(added, state);\n    updateManyMutably(updated, state);\n  }\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably)\n  };\n}","import type { IdSelector, Comparer, EntityStateAdapter, Update, EntityId, DraftableEntityState } from './models';\nimport { createStateOperator } from './state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport { selectIdValue, ensureEntitiesArray, splitAddedUpdatedEntities, getCurrent } from './utils';\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): number {\n  let lowIndex = 0;\n  let highIndex = sortedItems.length;\n  while (lowIndex < highIndex) {\n    let middleIndex = lowIndex + highIndex >>> 1;\n    const currentItem = sortedItems[middleIndex];\n    const res = comparisonFunction(item, currentItem);\n    if (res >= 0) {\n      lowIndex = middleIndex + 1;\n    } else {\n      highIndex = middleIndex;\n    }\n  }\n  return lowIndex;\n}\nexport function insert<T>(sortedItems: T[], item: T, comparisonFunction: Comparer<T>): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n  sortedItems.splice(insertAtIndex, 0, item);\n  return sortedItems;\n}\nexport function createSortedStateAdapter<T, Id extends EntityId>(selectId: IdSelector<T, Id>, comparer: Comparer<T>): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>;\n  const {\n    removeOne,\n    removeMany,\n    removeAll\n  } = createUnsortedStateAdapter(selectId);\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state);\n  }\n  function addManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R, existingIds?: Id[]): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids));\n    const addedKeys = new Set<Id>();\n    const models = newEntities.filter(model => {\n      const modelId = selectIdValue(model, selectId);\n      const notAdded = !addedKeys.has(modelId);\n      if (notAdded) addedKeys.add(modelId);\n      return !existingKeys.has(modelId) && notAdded;\n    });\n    if (models.length !== 0) {\n      mergeFunction(state, models);\n    }\n  }\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state);\n  }\n  function setManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    let deduplicatedEntities = {} as Record<Id, T>;\n    newEntities = ensureEntitiesArray(newEntities);\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        const entityId = selectId(item);\n        // For multiple items with the same ID, we should keep the last one.\n        deduplicatedEntities[entityId] = item;\n        delete (state.entities as Record<Id, T>)[entityId];\n      }\n      newEntities = ensureEntitiesArray(deduplicatedEntities);\n      mergeFunction(state, newEntities);\n    }\n  }\n  function setAllMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    newEntities = ensureEntitiesArray(newEntities);\n    state.entities = {} as Record<Id, T>;\n    state.ids = [];\n    addManyMutably(newEntities, state, []);\n  }\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state);\n  }\n  function updateManyMutably(updates: ReadonlyArray<Update<T, Id>>, state: R): void {\n    let appliedUpdates = false;\n    let replacedIds = false;\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id];\n      if (!entity) {\n        continue;\n      }\n      appliedUpdates = true;\n      Object.assign(entity, update.changes);\n      const newId = selectId(entity);\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true;\n        delete (state.entities as Record<Id, T>)[update.id];\n        const oldIndex = (state.ids as Id[]).indexOf(update.id);\n        state.ids[oldIndex] = newId;\n        (state.entities as Record<Id, T>)[newId] = entity;\n      }\n    }\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds);\n    }\n  }\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state);\n  }\n  function upsertManyMutably(newEntities: readonly T[] | Record<Id, T>, state: R): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(newEntities, selectId, state);\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray);\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state);\n    }\n  }\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue;\n      }\n      return false;\n    }\n    return true;\n  }\n  type MergeFunction = (state: R, addedItems: readonly T[], appliedUpdates?: boolean, replacedIds?: boolean) => void;\n  const mergeFunction: MergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n    const currentEntities = getCurrent(state.entities);\n    const currentIds = getCurrent(state.ids);\n    const stateEntities = state.entities as Record<Id, T>;\n    let ids: Iterable<Id> = currentIds;\n    if (replacedIds) {\n      ids = new Set(currentIds);\n    }\n    let sortedEntities: T[] = [];\n    for (const id of ids) {\n      const entity = currentEntities[id];\n      if (entity) {\n        sortedEntities.push(entity);\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0;\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item;\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer);\n      }\n    }\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer);\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer);\n    }\n    const newSortedIds = sortedEntities.map(selectId);\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds;\n    }\n  };\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably)\n  };\n}","import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models';\nimport { createInitialStateFactory } from './entity_state';\nimport { createSelectorsFactory } from './state_selectors';\nimport { createSortedStateAdapter } from './sorted_state_adapter';\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter';\nimport type { WithRequiredProp } from '../tsHelpers';\nexport function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;\nexport function createEntityAdapter<T extends {\n  id: EntityId;\n}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(options: EntityAdapterOptions<T, EntityId> = {}): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options\n  };\n  const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n  const stateFactory = createInitialStateFactory(stateAdapter);\n  const selectorsFactory = createSelectorsFactory<T, EntityId>();\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter\n  };\n}","import type { SerializedError } from '@reduxjs/toolkit';\nconst task = 'task';\nconst listener = 'listener';\nconst completed = 'completed';\nconst cancelled = 'cancelled';\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const;\nexport const taskCompleted = `task-${completed}` as const;\nexport const listenerCancelled = `${listener}-${cancelled}` as const;\nexport const listenerCompleted = `${listener}-${completed}` as const;\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError';\n  message: string;\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`;\n  }\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nexport const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown = (func: unknown, expected: string) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(32) : `${expected} is not a function`);\n  }\n};\nexport const noop = () => {};\nexport const catchRejection = <T,>(promise: Promise<T>, onError = noop): Promise<T> => {\n  promise.catch(onError);\n  return promise;\n};\nexport const addAbortSignalListener = (abortSignal: AbortSignal, callback: (evt: Event) => void) => {\n  abortSignal.addEventListener('abort', callback, {\n    once: true\n  });\n  return () => abortSignal.removeEventListener('abort', callback);\n};","import { TaskAbortError } from './exceptions';\nimport type { TaskResult } from './types';\nimport { addAbortSignalListener, catchRejection, noop } from './utils';\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @see {TaskAbortError}\n * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    throw new TaskAbortError(signal.reason);\n  }\n};\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(signal: AbortSignal, promise: Promise<T>): Promise<T> {\n  let cleanup = noop;\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n    if (signal.aborted) {\n      notifyRejection();\n      return;\n    }\n    cleanup = addAbortSignalListener(signal, notifyRejection);\n    promise.finally(() => cleanup()).then(resolve, reject);\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop;\n  });\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T,>(task: () => Promise<T>, cleanUp?: () => void): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve();\n    const value = await task();\n    return {\n      status: 'ok',\n      value\n    };\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error\n    };\n  } finally {\n    cleanUp?.();\n  }\n};\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T,>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(raceWithSignal(signal, promise).then(output => {\n      validateActive(signal);\n      return output;\n    }));\n  };\n};\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal);\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>(resolve => setTimeout(resolve, timeoutMs)));\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux';\nimport { isAction } from '../reduxImports';\nimport type { ThunkDispatch } from 'redux-thunk';\nimport { createAction } from '../createAction';\nimport { nanoid } from '../nanoid';\nimport { TaskAbortError, listenerCancelled, listenerCompleted, taskCancelled, taskCompleted } from './exceptions';\nimport { createDelay, createPause, raceWithSignal, runTask, validateActive } from './task';\nimport type { AddListenerOverloads, AnyListenerPredicate, CreateListenerMiddlewareOptions, FallbackAddListenerOptions, ForkOptions, ForkedTask, ForkedTaskExecutor, ListenerEntry, ListenerErrorHandler, ListenerErrorInfo, ListenerMiddleware, ListenerMiddlewareInstance, TakePattern, TaskResult, TypedAddListener, TypedCreateListenerEntry, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\nimport { addAbortSignalListener, assertFunction, catchRejection, noop } from './utils';\nexport { TaskAbortError } from './exceptions';\nexport type { AsyncTaskExecutor, CreateListenerMiddlewareOptions, ForkedTask, ForkedTaskAPI, ForkedTaskExecutor, ListenerEffect, ListenerEffectAPI, ListenerErrorHandler, ListenerMiddleware, ListenerMiddlewareInstance, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, TypedAddListener, TypedRemoveListener, TypedStartListening, TypedStopListening, UnsubscribeListener, UnsubscribeListenerOptions } from './types';\n\n//Overly-aggressive byte-shaving\nconst {\n  assign\n} = Object;\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const;\nconst alm = 'listenerMiddleware' as const;\nconst createFork = (parentAbortSignal: AbortSignal, parentBlockingPromises: Promise<any>[]) => {\n  const linkControllers = (controller: AbortController) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));\n  return <T,>(taskExecutor: ForkedTaskExecutor<T>, opts?: ForkOptions): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor');\n    const childAbortController = new AbortController();\n    linkControllers(childAbortController);\n    const result = runTask<T>(async (): Promise<T> => {\n      validateActive(parentAbortSignal);\n      validateActive(childAbortController.signal);\n      const result = (await taskExecutor({\n        pause: createPause(childAbortController.signal),\n        delay: createDelay(childAbortController.signal),\n        signal: childAbortController.signal\n      })) as T;\n      validateActive(childAbortController.signal);\n      return result;\n    }, () => childAbortController.abort(taskCompleted));\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop));\n    }\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        childAbortController.abort(taskCancelled);\n      }\n    };\n  };\n};\nconst createTakePattern = <S,>(startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>, signal: AbortSignal): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>,>(predicate: P, timeout: number | undefined) => {\n    validateActive(signal);\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {};\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe();\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n        }\n      });\n      unsubscribe = () => {\n        stopListening();\n        reject();\n      };\n    });\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise];\n    if (timeout != null) {\n      promises.push(new Promise<null>(resolve => setTimeout(resolve, timeout, null)));\n    }\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises));\n      validateActive(signal);\n      return output;\n    } finally {\n      // Always clean up the listener\n      unsubscribe();\n    }\n  };\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) => catchRejection(take(predicate, timeout))) as TakePattern<S>;\n};\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let {\n    type,\n    actionCreator,\n    matcher,\n    predicate,\n    effect\n  } = options;\n  if (type) {\n    predicate = createAction(type).match;\n  } else if (actionCreator) {\n    type = actionCreator!.type;\n    predicate = actionCreator.match;\n  } else if (matcher) {\n    predicate = matcher;\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(21) : 'Creating or removing a listener requires one of the known fields for matching an action');\n  }\n  assertFunction(effect, 'options.listener');\n  return {\n    predicate,\n    type,\n    effect\n  };\n};\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> = /* @__PURE__ */assign((options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    predicate,\n    effect\n  } = getListenerEntryPropsFrom(options);\n  const entry: ListenerEntry<unknown> = {\n    id: nanoid(),\n    effect,\n    type,\n    predicate,\n    pending: new Set<AbortController>(),\n    unsubscribe: () => {\n      throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(22) : 'Unsubscribe not initialized');\n    }\n  };\n  return entry;\n}, {\n  withTypes: () => createListenerEntry\n}) as unknown as TypedCreateListenerEntry<unknown>;\nconst findListenerEntry = (listenerMap: Map<string, ListenerEntry>, options: FallbackAddListenerOptions) => {\n  const {\n    type,\n    effect,\n    predicate\n  } = getListenerEntryPropsFrom(options);\n  return Array.from(listenerMap.values()).find(entry => {\n    const matchPredicateOrType = typeof type === 'string' ? entry.type === type : entry.predicate === predicate;\n    return matchPredicateOrType && entry.effect === effect;\n  });\n};\nconst cancelActiveListeners = (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>) => {\n  entry.pending.forEach(controller => {\n    controller.abort(listenerCancelled);\n  });\n};\nconst createClearListenerMiddleware = (listenerMap: Map<string, ListenerEntry>, executingListeners: Map<ListenerEntry, number>) => {\n  return () => {\n    for (const listener of executingListeners.keys()) {\n      cancelActiveListeners(listener);\n    }\n    listenerMap.clear();\n  };\n};\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (errorHandler: ListenerErrorHandler, errorToNotify: unknown, errorInfo: ListenerErrorInfo): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo);\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError;\n    }, 0);\n  }\n};\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/add`), {\n  withTypes: () => addListener\n}) as unknown as TypedAddListener<unknown>;\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */createAction(`${alm}/removeAll`);\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */assign(/* @__PURE__ */createAction(`${alm}/remove`), {\n  withTypes: () => removeListener\n}) as unknown as TypedRemoveListener<unknown>;\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args);\n};\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {}) => {\n  const listenerMap = new Map<string, ListenerEntry>();\n\n  // Track listeners whose effect is currently executing so clearListeners can\n  // abort even listeners that have become unsubscribed while executing.\n  const executingListeners = new Map<ListenerEntry, number>();\n  const trackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 0;\n    executingListeners.set(entry, count + 1);\n  };\n  const untrackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 1;\n    if (count === 1) {\n      executingListeners.delete(entry);\n    } else {\n      executingListeners.set(entry, count - 1);\n    }\n  };\n  const {\n    extra,\n    onError = defaultErrorHandler\n  } = middlewareOptions;\n  assertFunction(onError, 'onError');\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id);\n    listenerMap.set(entry.id, entry);\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe();\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    };\n  };\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options as any);\n    return insertEntry(entry);\n  }) as AddListenerOverloads<any>;\n  assign(startListening, {\n    withTypes: () => startListening\n  });\n  const stopListening = (options: FallbackAddListenerOptions & UnsubscribeListenerOptions): boolean => {\n    const entry = findListenerEntry(listenerMap, options);\n    if (entry) {\n      entry.unsubscribe();\n      if (options.cancelActive) {\n        cancelActiveListeners(entry);\n      }\n    }\n    return !!entry;\n  };\n  assign(stopListening, {\n    withTypes: () => stopListening\n  });\n  const notifyListener = async (entry: ListenerEntry<unknown, Dispatch<UnknownAction>>, action: unknown, api: MiddlewareAPI, getOriginalState: () => StateType) => {\n    const internalTaskController = new AbortController();\n    const take = createTakePattern(startListening as AddListenerOverloads<any>, internalTaskController.signal);\n    const autoJoinPromises: Promise<any>[] = [];\n    try {\n      entry.pending.add(internalTaskController);\n      trackExecutingListener(entry);\n      await Promise.resolve(entry.effect(action,\n      // Use assign() rather than ... to avoid extra helper functions added to bundle\n      assign({}, api, {\n        getOriginalState,\n        condition: (predicate: AnyListenerPredicate<any>, timeout?: number) => take(predicate, timeout).then(Boolean),\n        take,\n        delay: createDelay(internalTaskController.signal),\n        pause: createPause<any>(internalTaskController.signal),\n        extra,\n        signal: internalTaskController.signal,\n        fork: createFork(internalTaskController.signal, autoJoinPromises),\n        unsubscribe: entry.unsubscribe,\n        subscribe: () => {\n          listenerMap.set(entry.id, entry);\n        },\n        cancelActiveListeners: () => {\n          entry.pending.forEach((controller, _, set) => {\n            if (controller !== internalTaskController) {\n              controller.abort(listenerCancelled);\n              set.delete(controller);\n            }\n          });\n        },\n        cancel: () => {\n          internalTaskController.abort(listenerCancelled);\n          entry.pending.delete(internalTaskController);\n        },\n        throwIfCancelled: () => {\n          validateActive(internalTaskController.signal);\n        }\n      })));\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect'\n        });\n      }\n    } finally {\n      await Promise.all(autoJoinPromises);\n      internalTaskController.abort(listenerCompleted); // Notify that the task has completed\n      untrackExecutingListener(entry);\n      entry.pending.delete(internalTaskController);\n    }\n  };\n  const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);\n  const middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument> = api => next => action => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action);\n    }\n    if (addListener.match(action)) {\n      return startListening(action.payload as any);\n    }\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware();\n      return;\n    }\n    if (removeListener.match(action)) {\n      return stopListening(action.payload);\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState();\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(23) : `${alm}: getOriginalState can only be called synchronously`);\n      }\n      return originalState as StateType;\n    };\n    let result: unknown;\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action);\n      if (listenerMap.size > 0) {\n        const currentState = api.getState();\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values());\n        for (const entry of listenerEntries) {\n          let runListener = false;\n          try {\n            runListener = entry.predicate(action, currentState, originalState);\n          } catch (predicateError) {\n            runListener = false;\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate'\n            });\n          }\n          if (!runListener) {\n            continue;\n          }\n          notifyListener(entry, action, api, getOriginalState);\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN;\n    }\n    return result;\n  };\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;\n};","import type { Dispatch, Middleware, UnknownAction } from 'redux';\nimport { compose } from '../reduxImports';\nimport { createAction } from '../createAction';\nimport { isAllOf } from '../matchers';\nimport { nanoid } from '../nanoid';\nimport { getOrInsertComputed } from '../utils';\nimport type { AddMiddleware, DynamicMiddleware, DynamicMiddlewareInstance, MiddlewareEntry, WithMiddleware } from './types';\nexport type { DynamicMiddlewareInstance, GetDispatchType as GetDispatch, MiddlewareApiConfig } from './types';\nconst createMiddlewareEntry = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(middleware: Middleware<any, State, DispatchType>): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map()\n});\nconst matchInstance = (instanceId: string) => (action: any): action is {\n  meta: {\n    instanceId: string;\n  };\n} => action?.meta?.instanceId === instanceId;\nexport const createDynamicMiddleware = <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid();\n  const middlewareMap = new Map<Middleware<any, State, DispatchType>, MiddlewareEntry<State, DispatchType>>();\n  const withMiddleware = Object.assign(createAction('dynamicMiddleware/add', (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n    payload: middlewares,\n    meta: {\n      instanceId\n    }\n  })), {\n    withTypes: () => withMiddleware\n  }) as WithMiddleware<State, DispatchType>;\n  const addMiddleware = Object.assign(function addMiddleware(...middlewares: Middleware<any, State, DispatchType>[]) {\n    middlewares.forEach(middleware => {\n      getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);\n    });\n  }, {\n    withTypes: () => addMiddleware\n  }) as AddMiddleware<State, DispatchType>;\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = api => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map(entry => getOrInsertComputed(entry.applied, api, entry.middleware));\n    return compose(...appliedMiddleware);\n  };\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n  const middleware: DynamicMiddleware<State, DispatchType> = api => next => action => {\n    if (isWithMiddleware(action)) {\n      addMiddleware(...action.payload);\n      return api.dispatch;\n    }\n    return getFinalMiddleware(api)(next)(action);\n  };\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId\n  };\n};","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2 } from \"@reduxjs/toolkit\";\nimport type { PreloadedStateShapeFromReducersMapObject, Reducer, StateFromReducersMapObject, UnknownAction } from 'redux';\nimport { combineReducers } from 'redux';\nimport { nanoid } from './nanoid';\nimport type { Id, NonUndefined, Tail, UnionToIntersection, WithOptionalProp } from './tsHelpers';\nimport { getOrInsertComputed } from './utils';\ntype SliceLike<ReducerPath extends string, State, PreloadedState = State> = {\n  reducerPath: ReducerPath;\n  reducer: Reducer<State, any, PreloadedState>;\n};\ntype AnySliceLike = SliceLike<string, any>;\ntype SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;\ntype SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;\ntype SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;\nexport type WithSlice<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikeState<A> };\nexport type WithSlicePreloadedState<A extends AnySliceLike> = { [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A> };\ntype ReducerMap = Record<string, Reducer>;\ntype ExistingSliceLike<DeclaredState, PreloadedState> = { [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>> }[keyof DeclaredState];\nexport type InjectConfig = {\n  /**\n   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.\n   */\n  overrideExisting?: boolean;\n};\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;\n  };\n}\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;\ntype InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;\nconst isSliceLike = (maybeSliceLike: AnySliceLike | ReducerMap): maybeSliceLike is AnySliceLike => 'reducerPath' in maybeSliceLike && typeof maybeSliceLike.reducerPath === 'string';\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) => slices.flatMap<[string, Reducer]>(sliceOrMap => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original');\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE];\nconst stateProxyMap = new WeakMap<object, object>();\nconst createStateProxy = <State extends object,>(state: State, reducerMap: Partial<Record<PropertyKey, Reducer>>, initialStateCache: Record<PropertyKey, unknown>) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {\n  get: (target, prop, receiver) => {\n    if (prop === ORIGINAL_STATE) return target;\n    const result = Reflect.get(target, prop, receiver);\n    if (typeof result === 'undefined') {\n      const cached = initialStateCache[prop];\n      if (typeof cached !== 'undefined') return cached;\n      const reducer = reducerMap[prop];\n      if (reducer) {\n        // ensure action type is random, to prevent reducer treating it differently\n        const reducerResult = reducer(undefined, {\n          type: nanoid()\n        });\n        if (typeof reducerResult === 'undefined') {\n          throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). ` + `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + `you can use null instead of undefined.`);\n        }\n        initialStateCache[prop] = reducerResult;\n        return reducerResult;\n      }\n    }\n    return result;\n  }\n})) as State;\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(25) : 'original must be used on state Proxy');\n  }\n  return state[ORIGINAL_STATE];\n};\nconst emptyObject = {};\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state;\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>> {\n  const reducerMap = Object.fromEntries(getReducers(slices));\n  const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;\n  let reducer = getReducer();\n  function combinedReducer(state: Record<string, unknown>, action: UnknownAction) {\n    return reducer(state, action);\n  }\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n  const initialStateCache: Record<PropertyKey, unknown> = {};\n  const inject = (slice: AnySliceLike, config: InjectConfig = {}): typeof combinedReducer => {\n    const {\n      reducerPath,\n      reducer: reducerToInject\n    } = slice;\n    const currentReducer = reducerMap[reducerPath];\n    if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n      if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n        console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n      }\n      return combinedReducer;\n    }\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath];\n    }\n    reducerMap[reducerPath] = reducerToInject;\n    reducer = getReducer();\n    return combinedReducer;\n  };\n  const selector = Object.assign(function makeSelector<State extends object, RootState, Args extends any[]>(selectorFn: (state: State, ...args: Args) => any, selectState?: (rootState: RootState, ...args: Args) => State) {\n    return function selector(state: State, ...args: Args) {\n      return selectorFn(createStateProxy(selectState ? selectState(state as any, ...args) : state, reducerMap, initialStateCache), ...args);\n    };\n  }, {\n    original\n  });\n  return Object.assign(combinedReducer, {\n    inject,\n    selector\n  }) as any;\n}","/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` + 'use the non-minified dev environment for full errors. ';\n}"],"mappings":";AAGA,cAAc;AACd,SAAS,QAAQ,YAAAA,iBAAgB;;;ACJjC,SAAS,SAAS,SAAoB,SAAiB,aAAa,6BAA6B;;;ADOjG,SAAS,gBAAgB,kBAAkB;;;AEP3C,SAAS,uBAAuB,sBAAsB;;;ACE/C,IAAM,iCAA+D,IAAI,SAAoB;AAClG,QAAMC,kBAAkB,sBAA8B,GAAG,IAAI;AAC7D,QAAMC,2BAA0B,OAAO,OAAO,IAAIC,UAAoB;AACpE,U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QAAM,SAAS,CAAC,OAAqB,SAAuB,CAAC,MAA8B;AACzF,UAAM;AAAA,MACJ;AAAA,MACA,SAAS;AAAA,IACX,IAAI;AACJ,UAAM,iBAAiB,WAAW,WAAW;AAC7C,QAAI,CAAC,OAAO,oBAAoB,kBAAkB,mBAAmB,iBAAiB;AACpF,UAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,aAAa,eAAe;AAC5E,gBAAQ,MAAM,0DAA0D,WAAW,gDAAgD;AAAA,MACrI;AACA,aAAO;AAAA,IACT;AACA,QAAI,OAAO,oBAAoB,mBAAmB,iBAAiB;AACjE,aAAO,kBAAkB,WAAW;AAAA,IACtC;AACA,eAAW,WAAW,IAAI;AAC1B,cAAU,WAAW;AACrB,WAAO;AAAA,EACT;AACA,QAAM,WAAW,OAAO,OAAO,SAAS,aAAkE,YAAkD,aAA8D;AACxN,WAAO,SAASC,UAAS,UAAiB,MAAY;AACpD,aAAO,WAAW,iBAAiB,cAAc,YAAY,OAAc,GAAG,IAAI,IAAI,OAAO,YAAY,iBAAiB,GAAG,GAAG,IAAI;AAAA,IACtI;AAAA,EACF,GAAG;AAAA,IACD;AAAA,EACF,CAAC;AACD,SAAO,OAAO,OAAO,iBAAiB;AAAA,IACpC;AAAA,IACA;AAAA,EACF,CAAC;AACH;;;AC9SO,SAAS,uBAAuB,MAAc;AACnD,SAAO,iCAAiC,IAAI,oDAAoD,IAAI;AACtG;","names":["original","createSelector","createDraftSafeSelector","args","noop","isActionCreator","stringify","getSerialize","listener","middleware","reducer","createAsyncThunk","ReducerType","createSlice","reducer","name","reducerPath","createSelector","arg","original","noop","noop","task","result","noop","listener","addMiddleware","middleware","combineReducers","combineReducers","selector"]}
Index: node_modules/@reduxjs/toolkit/dist/uncheckedindexed.ts
===================================================================
--- node_modules/@reduxjs/toolkit/dist/uncheckedindexed.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/dist/uncheckedindexed.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,16 @@
+// inlined from https://github.com/EskiMojo14/uncheckedindexed
+// relies on remaining as a TS file, not .d.ts
+type IfMaybeUndefined<T, True, False> = [undefined] extends [T] ? True : False
+
+const testAccess = ({} as Record<string, 0>)['a']
+
+export type IfUncheckedIndexedAccess<True, False> = IfMaybeUndefined<
+  typeof testAccess,
+  True,
+  False
+>
+
+export type UncheckedIndexedAccess<T> = IfUncheckedIndexedAccess<
+  T | undefined,
+  T
+>
Index: node_modules/@reduxjs/toolkit/node_modules/immer/LICENSE
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/LICENSE	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/LICENSE	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Michel Weststrate
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.development.js
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.development.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.development.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1691 @@
+"use strict";
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// src/immer.ts
+var immer_exports = {};
+__export(immer_exports, {
+  Immer: () => Immer2,
+  applyPatches: () => applyPatches,
+  castDraft: () => castDraft,
+  castImmutable: () => castImmutable,
+  createDraft: () => createDraft,
+  current: () => current,
+  enableArrayMethods: () => enableArrayMethods,
+  enableMapSet: () => enableMapSet,
+  enablePatches: () => enablePatches,
+  finishDraft: () => finishDraft,
+  freeze: () => freeze,
+  immerable: () => DRAFTABLE,
+  isDraft: () => isDraft,
+  isDraftable: () => isDraftable,
+  nothing: () => NOTHING,
+  original: () => original,
+  produce: () => produce,
+  produceWithPatches: () => produceWithPatches,
+  setAutoFreeze: () => setAutoFreeze,
+  setUseStrictIteration: () => setUseStrictIteration,
+  setUseStrictShallowCopy: () => setUseStrictShallowCopy
+});
+module.exports = __toCommonJS(immer_exports);
+
+// src/utils/env.ts
+var NOTHING = Symbol.for("immer-nothing");
+var DRAFTABLE = Symbol.for("immer-draftable");
+var DRAFT_STATE = Symbol.for("immer-state");
+
+// src/utils/errors.ts
+var errors = process.env.NODE_ENV !== "production" ? [
+  // All error codes, starting by 0:
+  function(plugin) {
+    return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
+  },
+  function(thing) {
+    return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
+  },
+  "This object has been frozen and should not be mutated",
+  function(data) {
+    return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
+  },
+  "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
+  "Immer forbids circular references",
+  "The first or second argument to `produce` must be a function",
+  "The third argument to `produce` must be a function or undefined",
+  "First argument to `createDraft` must be a plain object, an array, or an immerable object",
+  "First argument to `finishDraft` must be a draft returned by `createDraft`",
+  function(thing) {
+    return `'current' expects a draft, got: ${thing}`;
+  },
+  "Object.defineProperty() cannot be used on an Immer draft",
+  "Object.setPrototypeOf() cannot be used on an Immer draft",
+  "Immer only supports deleting array indices",
+  "Immer only supports setting array indices and the 'length' property",
+  function(thing) {
+    return `'original' expects a draft, got: ${thing}`;
+  }
+  // Note: if more errors are added, the errorOffset in Patches.ts should be increased
+  // See Patches.ts for additional errors
+] : [];
+function die(error, ...args) {
+  if (process.env.NODE_ENV !== "production") {
+    const e = errors[error];
+    const msg = isFunction(e) ? e.apply(null, args) : e;
+    throw new Error(`[Immer] ${msg}`);
+  }
+  throw new Error(
+    `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
+  );
+}
+
+// src/utils/common.ts
+var O = Object;
+var getPrototypeOf = O.getPrototypeOf;
+var CONSTRUCTOR = "constructor";
+var PROTOTYPE = "prototype";
+var CONFIGURABLE = "configurable";
+var ENUMERABLE = "enumerable";
+var WRITABLE = "writable";
+var VALUE = "value";
+var isDraft = (value) => !!value && !!value[DRAFT_STATE];
+function isDraftable(value) {
+  if (!value)
+    return false;
+  return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
+}
+var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
+var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
+function isPlainObject(value) {
+  if (!value || !isObjectish(value))
+    return false;
+  const proto = getPrototypeOf(value);
+  if (proto === null || proto === O[PROTOTYPE])
+    return true;
+  const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
+  if (Ctor === Object)
+    return true;
+  if (!isFunction(Ctor))
+    return false;
+  let ctorString = cachedCtorStrings.get(Ctor);
+  if (ctorString === void 0) {
+    ctorString = Function.toString.call(Ctor);
+    cachedCtorStrings.set(Ctor, ctorString);
+  }
+  return ctorString === objectCtorString;
+}
+function original(value) {
+  if (!isDraft(value))
+    die(15, value);
+  return value[DRAFT_STATE].base_;
+}
+function each(obj, iter, strict = true) {
+  if (getArchtype(obj) === 0 /* Object */) {
+    const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
+    keys.forEach((key) => {
+      iter(key, obj[key], obj);
+    });
+  } else {
+    obj.forEach((entry, index) => iter(index, entry, obj));
+  }
+}
+function getArchtype(thing) {
+  const state = thing[DRAFT_STATE];
+  return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
+}
+var has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
+var get = (thing, prop, type = getArchtype(thing)) => (
+  // @ts-ignore
+  type === 2 /* Map */ ? thing.get(prop) : thing[prop]
+);
+var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
+  if (type === 2 /* Map */)
+    thing.set(propOrOldValue, value);
+  else if (type === 3 /* Set */) {
+    thing.add(value);
+  } else
+    thing[propOrOldValue] = value;
+};
+function is(x, y) {
+  if (x === y) {
+    return x !== 0 || 1 / x === 1 / y;
+  } else {
+    return x !== x && y !== y;
+  }
+}
+var isArray = Array.isArray;
+var isMap = (target) => target instanceof Map;
+var isSet = (target) => target instanceof Set;
+var isObjectish = (target) => typeof target === "object";
+var isFunction = (target) => typeof target === "function";
+var isBoolean = (target) => typeof target === "boolean";
+function isArrayIndex(value) {
+  const n = +value;
+  return Number.isInteger(n) && String(n) === value;
+}
+var getProxyDraft = (value) => {
+  if (!isObjectish(value))
+    return null;
+  return value?.[DRAFT_STATE];
+};
+var latest = (state) => state.copy_ || state.base_;
+var getValue = (value) => {
+  const proxyDraft = getProxyDraft(value);
+  return proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value;
+};
+var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
+function shallowCopy(base, strict) {
+  if (isMap(base)) {
+    return new Map(base);
+  }
+  if (isSet(base)) {
+    return new Set(base);
+  }
+  if (isArray(base))
+    return Array[PROTOTYPE].slice.call(base);
+  const isPlain = isPlainObject(base);
+  if (strict === true || strict === "class_only" && !isPlain) {
+    const descriptors = O.getOwnPropertyDescriptors(base);
+    delete descriptors[DRAFT_STATE];
+    let keys = Reflect.ownKeys(descriptors);
+    for (let i = 0; i < keys.length; i++) {
+      const key = keys[i];
+      const desc = descriptors[key];
+      if (desc[WRITABLE] === false) {
+        desc[WRITABLE] = true;
+        desc[CONFIGURABLE] = true;
+      }
+      if (desc.get || desc.set)
+        descriptors[key] = {
+          [CONFIGURABLE]: true,
+          [WRITABLE]: true,
+          // could live with !!desc.set as well here...
+          [ENUMERABLE]: desc[ENUMERABLE],
+          [VALUE]: base[key]
+        };
+    }
+    return O.create(getPrototypeOf(base), descriptors);
+  } else {
+    const proto = getPrototypeOf(base);
+    if (proto !== null && isPlain) {
+      return { ...base };
+    }
+    const obj = O.create(proto);
+    return O.assign(obj, base);
+  }
+}
+function freeze(obj, deep = false) {
+  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
+    return obj;
+  if (getArchtype(obj) > 1) {
+    O.defineProperties(obj, {
+      set: dontMutateMethodOverride,
+      add: dontMutateMethodOverride,
+      clear: dontMutateMethodOverride,
+      delete: dontMutateMethodOverride
+    });
+  }
+  O.freeze(obj);
+  if (deep)
+    each(
+      obj,
+      (_key, value) => {
+        freeze(value, true);
+      },
+      false
+    );
+  return obj;
+}
+function dontMutateFrozenCollections() {
+  die(2);
+}
+var dontMutateMethodOverride = {
+  [VALUE]: dontMutateFrozenCollections
+};
+function isFrozen(obj) {
+  if (obj === null || !isObjectish(obj))
+    return true;
+  return O.isFrozen(obj);
+}
+
+// src/utils/plugins.ts
+var PluginMapSet = "MapSet";
+var PluginPatches = "Patches";
+var PluginArrayMethods = "ArrayMethods";
+var plugins = {};
+function getPlugin(pluginKey) {
+  const plugin = plugins[pluginKey];
+  if (!plugin) {
+    die(0, pluginKey);
+  }
+  return plugin;
+}
+var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
+function loadPlugin(pluginKey, implementation) {
+  if (!plugins[pluginKey])
+    plugins[pluginKey] = implementation;
+}
+
+// src/core/scope.ts
+var currentScope;
+var getCurrentScope = () => currentScope;
+var createScope = (parent_, immer_) => ({
+  drafts_: [],
+  parent_,
+  immer_,
+  // Whenever the modified draft contains a draft from another scope, we
+  // need to prevent auto-freezing so the unowned draft can be finalized.
+  canAutoFreeze_: true,
+  unfinalizedDrafts_: 0,
+  handledSet_: /* @__PURE__ */ new Set(),
+  processedForPatches_: /* @__PURE__ */ new Set(),
+  mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
+  arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
+});
+function usePatchesInScope(scope, patchListener) {
+  if (patchListener) {
+    scope.patchPlugin_ = getPlugin(PluginPatches);
+    scope.patches_ = [];
+    scope.inversePatches_ = [];
+    scope.patchListener_ = patchListener;
+  }
+}
+function revokeScope(scope) {
+  leaveScope(scope);
+  scope.drafts_.forEach(revokeDraft);
+  scope.drafts_ = null;
+}
+function leaveScope(scope) {
+  if (scope === currentScope) {
+    currentScope = scope.parent_;
+  }
+}
+var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
+function revokeDraft(draft) {
+  const state = draft[DRAFT_STATE];
+  if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
+    state.revoke_();
+  else
+    state.revoked_ = true;
+}
+
+// src/core/finalize.ts
+function processResult(result, scope) {
+  scope.unfinalizedDrafts_ = scope.drafts_.length;
+  const baseDraft = scope.drafts_[0];
+  const isReplaced = result !== void 0 && result !== baseDraft;
+  if (isReplaced) {
+    if (baseDraft[DRAFT_STATE].modified_) {
+      revokeScope(scope);
+      die(4);
+    }
+    if (isDraftable(result)) {
+      result = finalize(scope, result);
+    }
+    const { patchPlugin_ } = scope;
+    if (patchPlugin_) {
+      patchPlugin_.generateReplacementPatches_(
+        baseDraft[DRAFT_STATE].base_,
+        result,
+        scope
+      );
+    }
+  } else {
+    result = finalize(scope, baseDraft);
+  }
+  maybeFreeze(scope, result, true);
+  revokeScope(scope);
+  if (scope.patches_) {
+    scope.patchListener_(scope.patches_, scope.inversePatches_);
+  }
+  return result !== NOTHING ? result : void 0;
+}
+function finalize(rootScope, value) {
+  if (isFrozen(value))
+    return value;
+  const state = value[DRAFT_STATE];
+  if (!state) {
+    const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
+    return finalValue;
+  }
+  if (!isSameScope(state, rootScope)) {
+    return value;
+  }
+  if (!state.modified_) {
+    return state.base_;
+  }
+  if (!state.finalized_) {
+    const { callbacks_ } = state;
+    if (callbacks_) {
+      while (callbacks_.length > 0) {
+        const callback = callbacks_.pop();
+        callback(rootScope);
+      }
+    }
+    generatePatchesAndFinalize(state, rootScope);
+  }
+  return state.copy_;
+}
+function maybeFreeze(scope, value, deep = false) {
+  if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
+    freeze(value, deep);
+  }
+}
+function markStateFinalized(state) {
+  state.finalized_ = true;
+  state.scope_.unfinalizedDrafts_--;
+}
+var isSameScope = (state, rootScope) => state.scope_ === rootScope;
+var EMPTY_LOCATIONS_RESULT = [];
+function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
+  const parentCopy = latest(parent);
+  const parentType = parent.type_;
+  if (originalKey !== void 0) {
+    const currentValue = get(parentCopy, originalKey, parentType);
+    if (currentValue === draftValue) {
+      set(parentCopy, originalKey, finalizedValue, parentType);
+      return;
+    }
+  }
+  if (!parent.draftLocations_) {
+    const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
+    each(parentCopy, (key, value) => {
+      if (isDraft(value)) {
+        const keys = draftLocations.get(value) || [];
+        keys.push(key);
+        draftLocations.set(value, keys);
+      }
+    });
+  }
+  const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
+  for (const location of locations) {
+    set(parentCopy, location, finalizedValue, parentType);
+  }
+}
+function registerChildFinalizationCallback(parent, child, key) {
+  parent.callbacks_.push(function childCleanup(rootScope) {
+    const state = child;
+    if (!state || !isSameScope(state, rootScope)) {
+      return;
+    }
+    rootScope.mapSetPlugin_?.fixSetContents(state);
+    const finalizedValue = getFinalValue(state);
+    updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
+    generatePatchesAndFinalize(state, rootScope);
+  });
+}
+function generatePatchesAndFinalize(state, rootScope) {
+  const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);
+  if (shouldFinalize) {
+    const { patchPlugin_ } = rootScope;
+    if (patchPlugin_) {
+      const basePath = patchPlugin_.getPath(state);
+      if (basePath) {
+        patchPlugin_.generatePatches_(state, basePath, rootScope);
+      }
+    }
+    markStateFinalized(state);
+  }
+}
+function handleCrossReference(target, key, value) {
+  const { scope_ } = target;
+  if (isDraft(value)) {
+    const state = value[DRAFT_STATE];
+    if (isSameScope(state, scope_)) {
+      state.callbacks_.push(function crossReferenceCleanup() {
+        prepareCopy(target);
+        const finalizedValue = getFinalValue(state);
+        updateDraftInParent(target, value, finalizedValue, key);
+      });
+    }
+  } else if (isDraftable(value)) {
+    target.callbacks_.push(function nestedDraftCleanup() {
+      const targetCopy = latest(target);
+      if (target.type_ === 3 /* Set */) {
+        if (targetCopy.has(value)) {
+          handleValue(value, scope_.handledSet_, scope_);
+        }
+      } else {
+        if (get(targetCopy, key, target.type_) === value) {
+          if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {
+            handleValue(
+              get(target.copy_, key, target.type_),
+              scope_.handledSet_,
+              scope_
+            );
+          }
+        }
+      }
+    });
+  }
+}
+function handleValue(target, handledSet, rootScope) {
+  if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
+    return target;
+  }
+  if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
+    return target;
+  }
+  handledSet.add(target);
+  each(target, (key, value) => {
+    if (isDraft(value)) {
+      const state = value[DRAFT_STATE];
+      if (isSameScope(state, rootScope)) {
+        const updatedValue = getFinalValue(state);
+        set(target, key, updatedValue, target.type_);
+        markStateFinalized(state);
+      }
+    } else if (isDraftable(value)) {
+      handleValue(value, handledSet, rootScope);
+    }
+  });
+  return target;
+}
+
+// src/core/proxy.ts
+function createProxyProxy(base, parent) {
+  const baseIsArray = isArray(base);
+  const state = {
+    type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,
+    // Track which produce call this is associated with.
+    scope_: parent ? parent.scope_ : getCurrentScope(),
+    // True for both shallow and deep changes.
+    modified_: false,
+    // Used during finalization.
+    finalized_: false,
+    // Track which properties have been assigned (true) or deleted (false).
+    // actually instantiated in `prepareCopy()`
+    assigned_: void 0,
+    // The parent draft state.
+    parent_: parent,
+    // The base state.
+    base_: base,
+    // The base proxy.
+    draft_: null,
+    // set below
+    // The base copy with any updated values.
+    copy_: null,
+    // Called by the `produce` function.
+    revoke_: null,
+    isManual_: false,
+    // `callbacks` actually gets assigned in `createProxy`
+    callbacks_: void 0
+  };
+  let target = state;
+  let traps = objectTraps;
+  if (baseIsArray) {
+    target = [state];
+    traps = arrayTraps;
+  }
+  const { revoke, proxy } = Proxy.revocable(target, traps);
+  state.draft_ = proxy;
+  state.revoke_ = revoke;
+  return [proxy, state];
+}
+var objectTraps = {
+  get(state, prop) {
+    if (prop === DRAFT_STATE)
+      return state;
+    let arrayPlugin = state.scope_.arrayMethodsPlugin_;
+    const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === "string";
+    if (isArrayWithStringProp) {
+      if (arrayPlugin?.isArrayOperationMethod(prop)) {
+        return arrayPlugin.createMethodInterceptor(state, prop);
+      }
+    }
+    const source = latest(state);
+    if (!has(source, prop, state.type_)) {
+      return readPropFromProto(state, source, prop);
+    }
+    const value = source[prop];
+    if (state.finalized_ || !isDraftable(value)) {
+      return value;
+    }
+    if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(
+      state.operationMethod
+    ) && isArrayIndex(prop)) {
+      return value;
+    }
+    if (value === peek(state.base_, prop)) {
+      prepareCopy(state);
+      const childKey = state.type_ === 1 /* Array */ ? +prop : prop;
+      const childDraft = createProxy(state.scope_, value, state, childKey);
+      return state.copy_[childKey] = childDraft;
+    }
+    return value;
+  },
+  has(state, prop) {
+    return prop in latest(state);
+  },
+  ownKeys(state) {
+    return Reflect.ownKeys(latest(state));
+  },
+  set(state, prop, value) {
+    const desc = getDescriptorFromProto(latest(state), prop);
+    if (desc?.set) {
+      desc.set.call(state.draft_, value);
+      return true;
+    }
+    if (!state.modified_) {
+      const current2 = peek(latest(state), prop);
+      const currentState = current2?.[DRAFT_STATE];
+      if (currentState && currentState.base_ === value) {
+        state.copy_[prop] = value;
+        state.assigned_.set(prop, false);
+        return true;
+      }
+      if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))
+        return true;
+      prepareCopy(state);
+      markChanged(state);
+    }
+    if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
+    (value !== void 0 || prop in state.copy_) || // special case: NaN
+    Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
+      return true;
+    state.copy_[prop] = value;
+    state.assigned_.set(prop, true);
+    handleCrossReference(state, prop, value);
+    return true;
+  },
+  deleteProperty(state, prop) {
+    prepareCopy(state);
+    if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
+      state.assigned_.set(prop, false);
+      markChanged(state);
+    } else {
+      state.assigned_.delete(prop);
+    }
+    if (state.copy_) {
+      delete state.copy_[prop];
+    }
+    return true;
+  },
+  // Note: We never coerce `desc.value` into an Immer draft, because we can't make
+  // the same guarantee in ES5 mode.
+  getOwnPropertyDescriptor(state, prop) {
+    const owner = latest(state);
+    const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
+    if (!desc)
+      return desc;
+    return {
+      [WRITABLE]: true,
+      [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== "length",
+      [ENUMERABLE]: desc[ENUMERABLE],
+      [VALUE]: owner[prop]
+    };
+  },
+  defineProperty() {
+    die(11);
+  },
+  getPrototypeOf(state) {
+    return getPrototypeOf(state.base_);
+  },
+  setPrototypeOf() {
+    die(12);
+  }
+};
+var arrayTraps = {};
+for (let key in objectTraps) {
+  let fn = objectTraps[key];
+  arrayTraps[key] = function() {
+    const args = arguments;
+    args[0] = args[0][0];
+    return fn.apply(this, args);
+  };
+}
+arrayTraps.deleteProperty = function(state, prop) {
+  if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
+    die(13);
+  return arrayTraps.set.call(this, state, prop, void 0);
+};
+arrayTraps.set = function(state, prop, value) {
+  if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
+    die(14);
+  return objectTraps.set.call(this, state[0], prop, value, state[0]);
+};
+function peek(draft, prop) {
+  const state = draft[DRAFT_STATE];
+  const source = state ? latest(state) : draft;
+  return source[prop];
+}
+function readPropFromProto(state, source, prop) {
+  const desc = getDescriptorFromProto(source, prop);
+  return desc ? VALUE in desc ? desc[VALUE] : (
+    // This is a very special case, if the prop is a getter defined by the
+    // prototype, we should invoke it with the draft as context!
+    desc.get?.call(state.draft_)
+  ) : void 0;
+}
+function getDescriptorFromProto(source, prop) {
+  if (!(prop in source))
+    return void 0;
+  let proto = getPrototypeOf(source);
+  while (proto) {
+    const desc = Object.getOwnPropertyDescriptor(proto, prop);
+    if (desc)
+      return desc;
+    proto = getPrototypeOf(proto);
+  }
+  return void 0;
+}
+function markChanged(state) {
+  if (!state.modified_) {
+    state.modified_ = true;
+    if (state.parent_) {
+      markChanged(state.parent_);
+    }
+  }
+}
+function prepareCopy(state) {
+  if (!state.copy_) {
+    state.assigned_ = /* @__PURE__ */ new Map();
+    state.copy_ = shallowCopy(
+      state.base_,
+      state.scope_.immer_.useStrictShallowCopy_
+    );
+  }
+}
+
+// src/core/immerClass.ts
+var Immer2 = class {
+  constructor(config) {
+    this.autoFreeze_ = true;
+    this.useStrictShallowCopy_ = false;
+    this.useStrictIteration_ = false;
+    /**
+     * The `produce` function takes a value and a "recipe function" (whose
+     * return value often depends on the base state). The recipe function is
+     * free to mutate its first argument however it wants. All mutations are
+     * only ever applied to a __copy__ of the base state.
+     *
+     * Pass only a function to create a "curried producer" which relieves you
+     * from passing the recipe function every time.
+     *
+     * Only plain objects and arrays are made mutable. All other objects are
+     * considered uncopyable.
+     *
+     * Note: This function is __bound__ to its `Immer` instance.
+     *
+     * @param {any} base - the initial state
+     * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
+     * @param {Function} patchListener - optional function that will be called with all the patches produced here
+     * @returns {any} a new state, or the initial state if nothing was modified
+     */
+    this.produce = (base, recipe, patchListener) => {
+      if (isFunction(base) && !isFunction(recipe)) {
+        const defaultBase = recipe;
+        recipe = base;
+        const self = this;
+        return function curriedProduce(base2 = defaultBase, ...args) {
+          return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
+        };
+      }
+      if (!isFunction(recipe))
+        die(6);
+      if (patchListener !== void 0 && !isFunction(patchListener))
+        die(7);
+      let result;
+      if (isDraftable(base)) {
+        const scope = enterScope(this);
+        const proxy = createProxy(scope, base, void 0);
+        let hasError = true;
+        try {
+          result = recipe(proxy);
+          hasError = false;
+        } finally {
+          if (hasError)
+            revokeScope(scope);
+          else
+            leaveScope(scope);
+        }
+        usePatchesInScope(scope, patchListener);
+        return processResult(result, scope);
+      } else if (!base || !isObjectish(base)) {
+        result = recipe(base);
+        if (result === void 0)
+          result = base;
+        if (result === NOTHING)
+          result = void 0;
+        if (this.autoFreeze_)
+          freeze(result, true);
+        if (patchListener) {
+          const p = [];
+          const ip = [];
+          getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
+            patches_: p,
+            inversePatches_: ip
+          });
+          patchListener(p, ip);
+        }
+        return result;
+      } else
+        die(1, base);
+    };
+    this.produceWithPatches = (base, recipe) => {
+      if (isFunction(base)) {
+        return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
+      }
+      let patches, inversePatches;
+      const result = this.produce(base, recipe, (p, ip) => {
+        patches = p;
+        inversePatches = ip;
+      });
+      return [result, patches, inversePatches];
+    };
+    if (isBoolean(config?.autoFreeze))
+      this.setAutoFreeze(config.autoFreeze);
+    if (isBoolean(config?.useStrictShallowCopy))
+      this.setUseStrictShallowCopy(config.useStrictShallowCopy);
+    if (isBoolean(config?.useStrictIteration))
+      this.setUseStrictIteration(config.useStrictIteration);
+  }
+  createDraft(base) {
+    if (!isDraftable(base))
+      die(8);
+    if (isDraft(base))
+      base = current(base);
+    const scope = enterScope(this);
+    const proxy = createProxy(scope, base, void 0);
+    proxy[DRAFT_STATE].isManual_ = true;
+    leaveScope(scope);
+    return proxy;
+  }
+  finishDraft(draft, patchListener) {
+    const state = draft && draft[DRAFT_STATE];
+    if (!state || !state.isManual_)
+      die(9);
+    const { scope_: scope } = state;
+    usePatchesInScope(scope, patchListener);
+    return processResult(void 0, scope);
+  }
+  /**
+   * Pass true to automatically freeze all copies created by Immer.
+   *
+   * By default, auto-freezing is enabled.
+   */
+  setAutoFreeze(value) {
+    this.autoFreeze_ = value;
+  }
+  /**
+   * Pass true to enable strict shallow copy.
+   *
+   * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+   */
+  setUseStrictShallowCopy(value) {
+    this.useStrictShallowCopy_ = value;
+  }
+  /**
+   * Pass false to use faster iteration that skips non-enumerable properties
+   * but still handles symbols for compatibility.
+   *
+   * By default, strict iteration is enabled (includes all own properties).
+   */
+  setUseStrictIteration(value) {
+    this.useStrictIteration_ = value;
+  }
+  shouldUseStrictIteration() {
+    return this.useStrictIteration_;
+  }
+  applyPatches(base, patches) {
+    let i;
+    for (i = patches.length - 1; i >= 0; i--) {
+      const patch = patches[i];
+      if (patch.path.length === 0 && patch.op === "replace") {
+        base = patch.value;
+        break;
+      }
+    }
+    if (i > -1) {
+      patches = patches.slice(i + 1);
+    }
+    const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
+    if (isDraft(base)) {
+      return applyPatchesImpl(base, patches);
+    }
+    return this.produce(
+      base,
+      (draft) => applyPatchesImpl(draft, patches)
+    );
+  }
+};
+function createProxy(rootScope, value, parent, key) {
+  const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
+  const scope = parent?.scope_ ?? getCurrentScope();
+  scope.drafts_.push(draft);
+  state.callbacks_ = parent?.callbacks_ ?? [];
+  state.key_ = key;
+  if (parent && key !== void 0) {
+    registerChildFinalizationCallback(parent, state, key);
+  } else {
+    state.callbacks_.push(function rootDraftCleanup(rootScope2) {
+      rootScope2.mapSetPlugin_?.fixSetContents(state);
+      const { patchPlugin_ } = rootScope2;
+      if (state.modified_ && patchPlugin_) {
+        patchPlugin_.generatePatches_(state, [], rootScope2);
+      }
+    });
+  }
+  return draft;
+}
+
+// src/core/current.ts
+function current(value) {
+  if (!isDraft(value))
+    die(10, value);
+  return currentImpl(value);
+}
+function currentImpl(value) {
+  if (!isDraftable(value) || isFrozen(value))
+    return value;
+  const state = value[DRAFT_STATE];
+  let copy;
+  let strict = true;
+  if (state) {
+    if (!state.modified_)
+      return state.base_;
+    state.finalized_ = true;
+    copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
+    strict = state.scope_.immer_.shouldUseStrictIteration();
+  } else {
+    copy = shallowCopy(value, true);
+  }
+  each(
+    copy,
+    (key, childValue) => {
+      set(copy, key, currentImpl(childValue));
+    },
+    strict
+  );
+  if (state) {
+    state.finalized_ = false;
+  }
+  return copy;
+}
+
+// src/plugins/patches.ts
+function enablePatches() {
+  const errorOffset = 16;
+  if (process.env.NODE_ENV !== "production") {
+    errors.push(
+      'Sets cannot have "replace" patches.',
+      function(op) {
+        return "Unsupported patch operation: " + op;
+      },
+      function(path) {
+        return "Cannot apply patch, path doesn't resolve: " + path;
+      },
+      "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
+    );
+  }
+  function getPath(state, path = []) {
+    if (state.key_ !== void 0) {
+      const parentCopy = state.parent_.copy_ ?? state.parent_.base_;
+      const proxyDraft = getProxyDraft(get(parentCopy, state.key_));
+      const valueAtKey = get(parentCopy, state.key_);
+      if (valueAtKey === void 0) {
+        return null;
+      }
+      if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {
+        return null;
+      }
+      if (proxyDraft != null && proxyDraft.base_ !== state.base_) {
+        return null;
+      }
+      const isSet2 = state.parent_.type_ === 3 /* Set */;
+      let key;
+      if (isSet2) {
+        const setParent = state.parent_;
+        key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);
+      } else {
+        key = state.key_;
+      }
+      if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {
+        return null;
+      }
+      path.push(key);
+    }
+    if (state.parent_) {
+      return getPath(state.parent_, path);
+    }
+    path.reverse();
+    try {
+      resolvePath(state.copy_, path);
+    } catch (e) {
+      return null;
+    }
+    return path;
+  }
+  function resolvePath(base, path) {
+    let current2 = base;
+    for (let i = 0; i < path.length - 1; i++) {
+      const key = path[i];
+      current2 = get(current2, key);
+      if (!isObjectish(current2) || current2 === null) {
+        throw new Error(`Cannot resolve path at '${path.join("/")}'`);
+      }
+    }
+    return current2;
+  }
+  const REPLACE = "replace";
+  const ADD = "add";
+  const REMOVE = "remove";
+  function generatePatches_(state, basePath, scope) {
+    if (state.scope_.processedForPatches_.has(state)) {
+      return;
+    }
+    state.scope_.processedForPatches_.add(state);
+    const { patches_, inversePatches_ } = scope;
+    switch (state.type_) {
+      case 0 /* Object */:
+      case 2 /* Map */:
+        return generatePatchesFromAssigned(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+      case 1 /* Array */:
+        return generateArrayPatches(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+      case 3 /* Set */:
+        return generateSetPatches(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+    }
+  }
+  function generateArrayPatches(state, basePath, patches, inversePatches) {
+    let { base_, assigned_ } = state;
+    let copy_ = state.copy_;
+    if (copy_.length < base_.length) {
+      ;
+      [base_, copy_] = [copy_, base_];
+      [patches, inversePatches] = [inversePatches, patches];
+    }
+    const allReassigned = state.allIndicesReassigned_ === true;
+    for (let i = 0; i < base_.length; i++) {
+      const copiedItem = copy_[i];
+      const baseItem = base_[i];
+      const isAssigned = allReassigned || assigned_?.get(i.toString());
+      if (isAssigned && copiedItem !== baseItem) {
+        const childState = copiedItem?.[DRAFT_STATE];
+        if (childState && childState.modified_) {
+          continue;
+        }
+        const path = basePath.concat([i]);
+        patches.push({
+          op: REPLACE,
+          path,
+          // Need to maybe clone it, as it can in fact be the original value
+          // due to the base/copy inversion at the start of this function
+          value: clonePatchValueIfNeeded(copiedItem)
+        });
+        inversePatches.push({
+          op: REPLACE,
+          path,
+          value: clonePatchValueIfNeeded(baseItem)
+        });
+      }
+    }
+    for (let i = base_.length; i < copy_.length; i++) {
+      const path = basePath.concat([i]);
+      patches.push({
+        op: ADD,
+        path,
+        // Need to maybe clone it, as it can in fact be the original value
+        // due to the base/copy inversion at the start of this function
+        value: clonePatchValueIfNeeded(copy_[i])
+      });
+    }
+    for (let i = copy_.length - 1; base_.length <= i; --i) {
+      const path = basePath.concat([i]);
+      inversePatches.push({
+        op: REMOVE,
+        path
+      });
+    }
+  }
+  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
+    const { base_, copy_, type_ } = state;
+    each(state.assigned_, (key, assignedValue) => {
+      const origValue = get(base_, key, type_);
+      const value = get(copy_, key, type_);
+      const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
+      if (origValue === value && op === REPLACE)
+        return;
+      const path = basePath.concat(key);
+      patches.push(
+        op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }
+      );
+      inversePatches.push(
+        op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
+      );
+    });
+  }
+  function generateSetPatches(state, basePath, patches, inversePatches) {
+    let { base_, copy_ } = state;
+    let i = 0;
+    base_.forEach((value) => {
+      if (!copy_.has(value)) {
+        const path = basePath.concat([i]);
+        patches.push({
+          op: REMOVE,
+          path,
+          value
+        });
+        inversePatches.unshift({
+          op: ADD,
+          path,
+          value
+        });
+      }
+      i++;
+    });
+    i = 0;
+    copy_.forEach((value) => {
+      if (!base_.has(value)) {
+        const path = basePath.concat([i]);
+        patches.push({
+          op: ADD,
+          path,
+          value
+        });
+        inversePatches.unshift({
+          op: REMOVE,
+          path,
+          value
+        });
+      }
+      i++;
+    });
+  }
+  function generateReplacementPatches_(baseValue, replacement, scope) {
+    const { patches_, inversePatches_ } = scope;
+    patches_.push({
+      op: REPLACE,
+      path: [],
+      value: replacement === NOTHING ? void 0 : replacement
+    });
+    inversePatches_.push({
+      op: REPLACE,
+      path: [],
+      value: baseValue
+    });
+  }
+  function applyPatches_(draft, patches) {
+    patches.forEach((patch) => {
+      const { path, op } = patch;
+      let base = draft;
+      for (let i = 0; i < path.length - 1; i++) {
+        const parentType = getArchtype(base);
+        let p = path[i];
+        if (typeof p !== "string" && typeof p !== "number") {
+          p = "" + p;
+        }
+        if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === CONSTRUCTOR))
+          die(errorOffset + 3);
+        if (isFunction(base) && p === PROTOTYPE)
+          die(errorOffset + 3);
+        base = get(base, p);
+        if (!isObjectish(base))
+          die(errorOffset + 2, path.join("/"));
+      }
+      const type = getArchtype(base);
+      const value = deepClonePatchValue(patch.value);
+      const key = path[path.length - 1];
+      switch (op) {
+        case REPLACE:
+          switch (type) {
+            case 2 /* Map */:
+              return base.set(key, value);
+            case 3 /* Set */:
+              die(errorOffset);
+            default:
+              return base[key] = value;
+          }
+        case ADD:
+          switch (type) {
+            case 1 /* Array */:
+              return key === "-" ? base.push(value) : base.splice(key, 0, value);
+            case 2 /* Map */:
+              return base.set(key, value);
+            case 3 /* Set */:
+              return base.add(value);
+            default:
+              return base[key] = value;
+          }
+        case REMOVE:
+          switch (type) {
+            case 1 /* Array */:
+              return base.splice(key, 1);
+            case 2 /* Map */:
+              return base.delete(key);
+            case 3 /* Set */:
+              return base.delete(patch.value);
+            default:
+              return delete base[key];
+          }
+        default:
+          die(errorOffset + 1, op);
+      }
+    });
+    return draft;
+  }
+  function deepClonePatchValue(obj) {
+    if (!isDraftable(obj))
+      return obj;
+    if (isArray(obj))
+      return obj.map(deepClonePatchValue);
+    if (isMap(obj))
+      return new Map(
+        Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
+      );
+    if (isSet(obj))
+      return new Set(Array.from(obj).map(deepClonePatchValue));
+    const cloned = Object.create(getPrototypeOf(obj));
+    for (const key in obj)
+      cloned[key] = deepClonePatchValue(obj[key]);
+    if (has(obj, DRAFTABLE))
+      cloned[DRAFTABLE] = obj[DRAFTABLE];
+    return cloned;
+  }
+  function clonePatchValueIfNeeded(obj) {
+    if (isDraft(obj)) {
+      return deepClonePatchValue(obj);
+    } else
+      return obj;
+  }
+  loadPlugin(PluginPatches, {
+    applyPatches_,
+    generatePatches_,
+    generateReplacementPatches_,
+    getPath
+  });
+}
+
+// src/plugins/mapset.ts
+function enableMapSet() {
+  class DraftMap extends Map {
+    constructor(target, parent) {
+      super();
+      this[DRAFT_STATE] = {
+        type_: 2 /* Map */,
+        parent_: parent,
+        scope_: parent ? parent.scope_ : getCurrentScope(),
+        modified_: false,
+        finalized_: false,
+        copy_: void 0,
+        assigned_: void 0,
+        base_: target,
+        draft_: this,
+        isManual_: false,
+        revoked_: false,
+        callbacks_: []
+      };
+    }
+    get size() {
+      return latest(this[DRAFT_STATE]).size;
+    }
+    has(key) {
+      return latest(this[DRAFT_STATE]).has(key);
+    }
+    set(key, value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!latest(state).has(key) || latest(state).get(key) !== value) {
+        prepareMapCopy(state);
+        markChanged(state);
+        state.assigned_.set(key, true);
+        state.copy_.set(key, value);
+        state.assigned_.set(key, true);
+        handleCrossReference(state, key, value);
+      }
+      return this;
+    }
+    delete(key) {
+      if (!this.has(key)) {
+        return false;
+      }
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareMapCopy(state);
+      markChanged(state);
+      if (state.base_.has(key)) {
+        state.assigned_.set(key, false);
+      } else {
+        state.assigned_.delete(key);
+      }
+      state.copy_.delete(key);
+      return true;
+    }
+    clear() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (latest(state).size) {
+        prepareMapCopy(state);
+        markChanged(state);
+        state.assigned_ = /* @__PURE__ */ new Map();
+        each(state.base_, (key) => {
+          state.assigned_.set(key, false);
+        });
+        state.copy_.clear();
+      }
+    }
+    forEach(cb, thisArg) {
+      const state = this[DRAFT_STATE];
+      latest(state).forEach((_value, key, _map) => {
+        cb.call(thisArg, this.get(key), key, this);
+      });
+    }
+    get(key) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      const value = latest(state).get(key);
+      if (state.finalized_ || !isDraftable(value)) {
+        return value;
+      }
+      if (value !== state.base_.get(key)) {
+        return value;
+      }
+      const draft = createProxy(state.scope_, value, state, key);
+      prepareMapCopy(state);
+      state.copy_.set(key, draft);
+      return draft;
+    }
+    keys() {
+      return latest(this[DRAFT_STATE]).keys();
+    }
+    values() {
+      const iterator = this.keys();
+      return {
+        [Symbol.iterator]: () => this.values(),
+        next: () => {
+          const r = iterator.next();
+          if (r.done)
+            return r;
+          const value = this.get(r.value);
+          return {
+            done: false,
+            value
+          };
+        }
+      };
+    }
+    entries() {
+      const iterator = this.keys();
+      return {
+        [Symbol.iterator]: () => this.entries(),
+        next: () => {
+          const r = iterator.next();
+          if (r.done)
+            return r;
+          const value = this.get(r.value);
+          return {
+            done: false,
+            value: [r.value, value]
+          };
+        }
+      };
+    }
+    [(DRAFT_STATE, Symbol.iterator)]() {
+      return this.entries();
+    }
+  }
+  function proxyMap_(target, parent) {
+    const map = new DraftMap(target, parent);
+    return [map, map[DRAFT_STATE]];
+  }
+  function prepareMapCopy(state) {
+    if (!state.copy_) {
+      state.assigned_ = /* @__PURE__ */ new Map();
+      state.copy_ = new Map(state.base_);
+    }
+  }
+  class DraftSet extends Set {
+    constructor(target, parent) {
+      super();
+      this[DRAFT_STATE] = {
+        type_: 3 /* Set */,
+        parent_: parent,
+        scope_: parent ? parent.scope_ : getCurrentScope(),
+        modified_: false,
+        finalized_: false,
+        copy_: void 0,
+        base_: target,
+        draft_: this,
+        drafts_: /* @__PURE__ */ new Map(),
+        revoked_: false,
+        isManual_: false,
+        assigned_: void 0,
+        callbacks_: []
+      };
+    }
+    get size() {
+      return latest(this[DRAFT_STATE]).size;
+    }
+    has(value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!state.copy_) {
+        return state.base_.has(value);
+      }
+      if (state.copy_.has(value))
+        return true;
+      if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))
+        return true;
+      return false;
+    }
+    add(value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!this.has(value)) {
+        prepareSetCopy(state);
+        markChanged(state);
+        state.copy_.add(value);
+        handleCrossReference(state, value, value);
+      }
+      return this;
+    }
+    delete(value) {
+      if (!this.has(value)) {
+        return false;
+      }
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      markChanged(state);
+      return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (
+        /* istanbul ignore next */
+        false
+      ));
+    }
+    clear() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (latest(state).size) {
+        prepareSetCopy(state);
+        markChanged(state);
+        state.copy_.clear();
+      }
+    }
+    values() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      return state.copy_.values();
+    }
+    entries() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      return state.copy_.entries();
+    }
+    keys() {
+      return this.values();
+    }
+    [(DRAFT_STATE, Symbol.iterator)]() {
+      return this.values();
+    }
+    forEach(cb, thisArg) {
+      const iterator = this.values();
+      let result = iterator.next();
+      while (!result.done) {
+        cb.call(thisArg, result.value, result.value, this);
+        result = iterator.next();
+      }
+    }
+  }
+  function proxySet_(target, parent) {
+    const set2 = new DraftSet(target, parent);
+    return [set2, set2[DRAFT_STATE]];
+  }
+  function prepareSetCopy(state) {
+    if (!state.copy_) {
+      state.copy_ = /* @__PURE__ */ new Set();
+      state.base_.forEach((value) => {
+        if (isDraftable(value)) {
+          const draft = createProxy(state.scope_, value, state, value);
+          state.drafts_.set(value, draft);
+          state.copy_.add(draft);
+        } else {
+          state.copy_.add(value);
+        }
+      });
+    }
+  }
+  function assertUnrevoked(state) {
+    if (state.revoked_)
+      die(3, JSON.stringify(latest(state)));
+  }
+  function fixSetContents(target) {
+    if (target.type_ === 3 /* Set */ && target.copy_) {
+      const copy = new Set(target.copy_);
+      target.copy_.clear();
+      copy.forEach((value) => {
+        target.copy_.add(getValue(value));
+      });
+    }
+  }
+  loadPlugin(PluginMapSet, { proxyMap_, proxySet_, fixSetContents });
+}
+
+// src/plugins/arrayMethods.ts
+function enableArrayMethods() {
+  const SHIFTING_METHODS = /* @__PURE__ */ new Set(["shift", "unshift"]);
+  const QUEUE_METHODS = /* @__PURE__ */ new Set(["push", "pop"]);
+  const RESULT_RETURNING_METHODS = /* @__PURE__ */ new Set([
+    ...QUEUE_METHODS,
+    ...SHIFTING_METHODS
+  ]);
+  const REORDERING_METHODS = /* @__PURE__ */ new Set(["reverse", "sort"]);
+  const MUTATING_METHODS = /* @__PURE__ */ new Set([
+    ...RESULT_RETURNING_METHODS,
+    ...REORDERING_METHODS,
+    "splice"
+  ]);
+  const FIND_METHODS = /* @__PURE__ */ new Set(["find", "findLast"]);
+  const NON_MUTATING_METHODS = /* @__PURE__ */ new Set([
+    "filter",
+    "slice",
+    "concat",
+    "flat",
+    ...FIND_METHODS,
+    "findIndex",
+    "findLastIndex",
+    "some",
+    "every",
+    "indexOf",
+    "lastIndexOf",
+    "includes",
+    "join",
+    "toString",
+    "toLocaleString"
+  ]);
+  function isMutatingArrayMethod(method) {
+    return MUTATING_METHODS.has(method);
+  }
+  function isNonMutatingArrayMethod(method) {
+    return NON_MUTATING_METHODS.has(method);
+  }
+  function isArrayOperationMethod(method) {
+    return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method);
+  }
+  function enterOperation(state, method) {
+    state.operationMethod = method;
+  }
+  function exitOperation(state) {
+    state.operationMethod = void 0;
+  }
+  function executeArrayMethod(state, operation, markLength = true) {
+    prepareCopy(state);
+    const result = operation();
+    markChanged(state);
+    if (markLength)
+      state.assigned_.set("length", true);
+    return result;
+  }
+  function markAllIndicesReassigned(state) {
+    state.allIndicesReassigned_ = true;
+  }
+  function normalizeSliceIndex(index, length) {
+    if (index < 0) {
+      return Math.max(length + index, 0);
+    }
+    return Math.min(index, length);
+  }
+  function handleSimpleOperation(state, method, args) {
+    return executeArrayMethod(state, () => {
+      const result = state.copy_[method](...args);
+      if (SHIFTING_METHODS.has(method)) {
+        markAllIndicesReassigned(state);
+      }
+      return RESULT_RETURNING_METHODS.has(method) ? result : state.draft_;
+    });
+  }
+  function handleReorderingOperation(state, method, args) {
+    return executeArrayMethod(
+      state,
+      () => {
+        ;
+        state.copy_[method](...args);
+        markAllIndicesReassigned(state);
+        return state.draft_;
+      },
+      false
+    );
+  }
+  function createMethodInterceptor(state, originalMethod) {
+    return function interceptedMethod(...args) {
+      const method = originalMethod;
+      enterOperation(state, method);
+      try {
+        if (isMutatingArrayMethod(method)) {
+          if (RESULT_RETURNING_METHODS.has(method)) {
+            return handleSimpleOperation(state, method, args);
+          }
+          if (REORDERING_METHODS.has(method)) {
+            return handleReorderingOperation(state, method, args);
+          }
+          if (method === "splice") {
+            const res = executeArrayMethod(
+              state,
+              () => state.copy_.splice(...args)
+            );
+            markAllIndicesReassigned(state);
+            return res;
+          }
+        } else {
+          return handleNonMutatingOperation(state, method, args);
+        }
+      } finally {
+        exitOperation(state);
+      }
+    };
+  }
+  function handleNonMutatingOperation(state, method, args) {
+    const source = latest(state);
+    if (method === "filter") {
+      const predicate = args[0];
+      const result = [];
+      for (let i = 0; i < source.length; i++) {
+        if (predicate(source[i], i, source)) {
+          result.push(state.draft_[i]);
+        }
+      }
+      return result;
+    }
+    if (FIND_METHODS.has(method)) {
+      const predicate = args[0];
+      const isForward = method === "find";
+      const step = isForward ? 1 : -1;
+      const start = isForward ? 0 : source.length - 1;
+      for (let i = start; i >= 0 && i < source.length; i += step) {
+        if (predicate(source[i], i, source)) {
+          return state.draft_[i];
+        }
+      }
+      return void 0;
+    }
+    if (method === "slice") {
+      const rawStart = args[0] ?? 0;
+      const rawEnd = args[1] ?? source.length;
+      const start = normalizeSliceIndex(rawStart, source.length);
+      const end = normalizeSliceIndex(rawEnd, source.length);
+      const result = [];
+      for (let i = start; i < end; i++) {
+        result.push(state.draft_[i]);
+      }
+      return result;
+    }
+    return source[method](...args);
+  }
+  loadPlugin(PluginArrayMethods, {
+    createMethodInterceptor,
+    isArrayOperationMethod,
+    isMutatingArrayMethod
+  });
+}
+
+// src/immer.ts
+var immer = new Immer2();
+var produce = immer.produce;
+var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(
+  immer
+);
+var setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer);
+var setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(
+  immer
+);
+var setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(
+  immer
+);
+var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
+var createDraft = /* @__PURE__ */ immer.createDraft.bind(immer);
+var finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer);
+var castDraft = (value) => value;
+var castImmutable = (value) => value;
+// Annotate the CommonJS export names for ESM import in node:
+0 && (module.exports = {
+  Immer,
+  applyPatches,
+  castDraft,
+  castImmutable,
+  createDraft,
+  current,
+  enableArrayMethods,
+  enableMapSet,
+  enablePatches,
+  finishDraft,
+  freeze,
+  immerable,
+  isDraft,
+  isDraftable,
+  nothing,
+  original,
+  produce,
+  produceWithPatches,
+  setAutoFreeze,
+  setUseStrictIteration,
+  setUseStrictShallowCopy
+});
+//# sourceMappingURL=immer.cjs.development.js.map
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.development.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.development.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.development.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/immer.ts","../../src/utils/env.ts","../../src/utils/errors.ts","../../src/utils/common.ts","../../src/utils/plugins.ts","../../src/core/scope.ts","../../src/core/finalize.ts","../../src/core/proxy.ts","../../src/core/immerClass.ts","../../src/core/current.ts","../../src/plugins/patches.ts","../../src/plugins/mapset.ts","../../src/plugins/arrayMethods.ts"],"sourcesContent":["import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = /* @__PURE__ */ immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(\n\timmer\n)\n\n/**\n * Pass false to use loose iteration that only processes enumerable string properties.\n * This skips symbols and non-enumerable properties for maximum performance.\n *\n * By default, strict iteration is enabled (includes all own properties).\n */\nexport const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(\n\timmer\n)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = /* @__PURE__ */ immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport let castDraft = <T>(value: T): Draft<T> => value as any\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport let castImmutable = <T>(value: T): Immutable<T> => value as any\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableArrayMethods} from \"./plugins/arrayMethods\"\n","// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","import {isFunction} from \"../internal\"\n\nexport const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t  ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = isFunction(e) ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nconst O = Object\n\nexport const getPrototypeOf = O.getPrototypeOf\n\nexport const CONSTRUCTOR = \"constructor\"\nexport const PROTOTYPE = \"prototype\"\n\nexport const CONFIGURABLE = \"configurable\"\nexport const ENUMERABLE = \"enumerable\"\nexport const WRITABLE = \"writable\"\nexport const VALUE = \"value\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tisArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value[CONSTRUCTOR]?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()\nconst cachedCtorStrings = new WeakMap()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || !isObjectish(value)) return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null || proto === O[PROTOTYPE]) return true\n\n\tconst Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]\n\tif (Ctor === Object) return true\n\n\tif (!isFunction(Ctor)) return false\n\n\tlet ctorString = cachedCtorStrings.get(Ctor)\n\tif (ctorString === undefined) {\n\t\tctorString = Function.toString.call(Ctor)\n\t\tcachedCtorStrings.set(Ctor, ctorString)\n\t}\n\n\treturn ctorString === objectCtorString\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n *\n * @param obj The object to iterate over\n * @param iter The iterator function\n * @param strict When true (default), includes symbols and non-enumerable properties.\n *               When false, uses looseiteration over only enumerable string properties.\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tstrict?: boolean\n): void\nexport function each(obj: any, iter: any, strict: boolean = true) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\t// If strict, we do a full iteration including symbols and non-enumerable properties\n\t\t// Otherwise, we only iterate enumerable string properties for performance\n\t\tconst keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)\n\t\tkeys.forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport let has = (\n\tthing: any,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): boolean =>\n\ttype === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: O[PROTOTYPE].hasOwnProperty.call(thing, prop)\n\n/*#__PURE__*/\nexport let get = (\n\tthing: AnyMap | AnyObject,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): any =>\n\t// @ts-ignore\n\ttype === ArchType.Map ? thing.get(prop) : thing[prop]\n\n/*#__PURE__*/\nexport let set = (\n\tthing: any,\n\tpropOrOldValue: PropertyKey,\n\tvalue: any,\n\ttype = getArchtype(thing)\n) => {\n\tif (type === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (type === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\nexport let isArray = Array.isArray\n\n/*#__PURE__*/\nexport let isMap = (target: any): target is AnyMap => target instanceof Map\n\n/*#__PURE__*/\nexport let isSet = (target: any): target is AnySet => target instanceof Set\n\nexport let isObjectish = (target: any) => typeof target === \"object\"\n\nexport let isFunction = (target: any): target is Function =>\n\ttypeof target === \"function\"\n\nexport let isBoolean = (target: any): target is boolean =>\n\ttypeof target === \"boolean\"\n\nexport function isArrayIndex(value: string | number): value is number | string {\n\tconst n = +value\n\treturn Number.isInteger(n) && String(n) === value\n}\n\nexport let getProxyDraft = <T extends any>(value: T): ImmerState | null => {\n\tif (!isObjectish(value)) return null\n\treturn (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]\n}\n\n/*#__PURE__*/\nexport let latest = (state: ImmerState): any => state.copy_ || state.base_\n\nexport let getValue = <T extends object>(value: T): T => {\n\tconst proxyDraft = getProxyDraft(value)\n\treturn proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value\n}\n\nexport let getFinalValue = (state: ImmerState): any =>\n\tstate.modified_ ? state.copy_ : state.base_\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (isArray(base)) return Array[PROTOTYPE].slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = O.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc[WRITABLE] === false) {\n\t\t\t\tdesc[WRITABLE] = true\n\t\t\t\tdesc[CONFIGURABLE] = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\t[CONFIGURABLE]: true,\n\t\t\t\t\t[WRITABLE]: true, // could live with !!desc.set as well here...\n\t\t\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t\t\t[VALUE]: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn O.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = O.create(proto)\n\t\treturn O.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tO.defineProperties(obj, {\n\t\t\tset: dontMutateMethodOverride,\n\t\t\tadd: dontMutateMethodOverride,\n\t\t\tclear: dontMutateMethodOverride,\n\t\t\tdelete: dontMutateMethodOverride\n\t\t})\n\t}\n\tO.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.values (only string-like, enumerables) instead of each()\n\t\teach(\n\t\t\tobj,\n\t\t\t(_key, value) => {\n\t\t\t\tfreeze(value, true)\n\t\t\t},\n\t\t\tfalse\n\t\t)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nconst dontMutateMethodOverride = {\n\t[VALUE]: dontMutateFrozenCollections\n}\n\nexport function isFrozen(obj: any): boolean {\n\t// Fast path: primitives and null/undefined are always \"frozen\"\n\tif (obj === null || !isObjectish(obj)) return true\n\treturn O.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie,\n\tImmerScope,\n\tProxyArrayState\n} from \"../internal\"\n\nexport const PluginMapSet = \"MapSet\"\nexport const PluginPatches = \"Patches\"\nexport const PluginArrayMethods = \"ArrayMethods\"\n\nexport type PatchesPlugin = {\n\tgeneratePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\trootScope: ImmerScope\n\t): void\n\tgenerateReplacementPatches_(\n\t\tbase: any,\n\t\treplacement: any,\n\t\trootScope: ImmerScope\n\t): void\n\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\tgetPath: (state: ImmerState) => PatchPath | null\n}\n\nexport type MapSetPlugin = {\n\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]\n\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]\n\tfixSetContents: (state: ImmerState) => void\n}\n\nexport type ArrayMethodsPlugin = {\n\tcreateMethodInterceptor: (state: ProxyArrayState, method: string) => Function\n\tisArrayOperationMethod: (method: string) => boolean\n\tisMutatingArrayMethod: (method: string) => boolean\n}\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: PatchesPlugin\n\tMapSet?: MapSetPlugin\n\tArrayMethods?: ArrayMethodsPlugin\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>\n\t!!plugins[pluginKey]\n\nexport let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {\n\tdelete plugins[pluginKey]\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin,\n\tPatchesPlugin,\n\tMapSetPlugin,\n\tisPluginLoaded,\n\tPluginMapSet,\n\tPluginPatches,\n\tArrayMethodsPlugin,\n\tPluginArrayMethods\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tpatchPlugin_?: PatchesPlugin\n\tmapSetPlugin_?: MapSetPlugin\n\tarrayMethodsPlugin_?: ArrayMethodsPlugin\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n\thandledSet_: Set<any>\n\tprocessedForPatches_: Set<any>\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport let getCurrentScope = () => currentScope!\n\nlet createScope = (\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope => ({\n\tdrafts_: [],\n\tparent_,\n\timmer_,\n\t// Whenever the modified draft contains a draft from another scope, we\n\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\tcanAutoFreeze_: true,\n\tunfinalizedDrafts_: 0,\n\thandledSet_: new Set(),\n\tprocessedForPatches_: new Set(),\n\tmapSetPlugin_: isPluginLoaded(PluginMapSet)\n\t\t? getPlugin(PluginMapSet)\n\t\t: undefined,\n\tarrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods)\n\t\t? getPlugin(PluginArrayMethods)\n\t\t: undefined\n})\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tscope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport let enterScope = (immer: Immer) =>\n\t(currentScope = createScope(currentScope, immer))\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tget,\n\tPatch,\n\tlatest,\n\tprepareCopy,\n\tgetFinalValue,\n\tgetValue,\n\tProxyArrayState\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t}\n\t\tconst {patchPlugin_} = scope\n\t\tif (patchPlugin_) {\n\t\t\tpatchPlugin_.generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft)\n\t}\n\n\tmaybeFreeze(scope, result, true)\n\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\tif (!state) {\n\t\tconst finalValue = handleValue(value, rootScope.handledSet_, rootScope)\n\t\treturn finalValue\n\t}\n\n\t// Never finalize drafts owned by another scope\n\tif (!isSameScope(state, rootScope)) {\n\t\treturn value\n\t}\n\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\treturn state.base_\n\t}\n\n\tif (!state.finalized_) {\n\t\t// Execute all registered draft finalization callbacks\n\t\tconst {callbacks_} = state\n\t\tif (callbacks_) {\n\t\t\twhile (callbacks_.length > 0) {\n\t\t\t\tconst callback = callbacks_.pop()!\n\t\t\t\tcallback(rootScope)\n\t\t\t}\n\t\t}\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t}\n\n\t// By now the root copy has been fully updated throughout its tree\n\treturn state.copy_\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n\nfunction markStateFinalized(state: ImmerState) {\n\tstate.finalized_ = true\n\tstate.scope_.unfinalizedDrafts_--\n}\n\nlet isSameScope = (state: ImmerState, rootScope: ImmerScope) =>\n\tstate.scope_ === rootScope\n\n// A reusable empty array to avoid allocations\nconst EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []\n\n// Updates all references to a draft in its parent to the finalized value.\n// This handles cases where the same draft appears multiple times in the parent, or has been moved around.\nexport function updateDraftInParent(\n\tparent: ImmerState,\n\tdraftValue: any,\n\tfinalizedValue: any,\n\toriginalKey?: string | number | symbol\n): void {\n\tconst parentCopy = latest(parent)\n\tconst parentType = parent.type_\n\n\t// Fast path: Check if draft is still at original key\n\tif (originalKey !== undefined) {\n\t\tconst currentValue = get(parentCopy, originalKey, parentType)\n\t\tif (currentValue === draftValue) {\n\t\t\t// Still at original location, just update it\n\t\t\tset(parentCopy, originalKey, finalizedValue, parentType)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Slow path: Build reverse mapping of all children\n\t// to their indices in the parent, so that we can\n\t// replace all locations where this draft appears.\n\t// We only have to build this once per parent.\n\tif (!parent.draftLocations_) {\n\t\tconst draftLocations = (parent.draftLocations_ = new Map())\n\n\t\t// Use `each` which works on Arrays, Maps, and Objects\n\t\teach(parentCopy, (key, value) => {\n\t\t\tif (isDraft(value)) {\n\t\t\t\tconst keys = draftLocations.get(value) || []\n\t\t\t\tkeys.push(key)\n\t\t\t\tdraftLocations.set(value, keys)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Look up all locations where this draft appears\n\tconst locations =\n\t\tparent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT\n\n\t// Update all locations\n\tfor (const location of locations) {\n\t\tset(parentCopy, location, finalizedValue, parentType)\n\t}\n}\n\n// Register a callback to finalize a child draft when the parent draft is finalized.\n// This assumes there is a parent -> child relationship between the two drafts,\n// and we have a key to locate the child in the parent.\nexport function registerChildFinalizationCallback(\n\tparent: ImmerState,\n\tchild: ImmerState,\n\tkey: string | number | symbol\n) {\n\tparent.callbacks_.push(function childCleanup(rootScope) {\n\t\tconst state: ImmerState = child\n\n\t\t// Can only continue if this is a draft owned by this scope\n\t\tif (!state || !isSameScope(state, rootScope)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle potential set value finalization first\n\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t// Update all locations in the parent that referenced this draft\n\t\tupdateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t})\n}\n\nfunction generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {\n\tconst shouldFinalize =\n\t\tstate.modified_ &&\n\t\t!state.finalized_ &&\n\t\t(state.type_ === ArchType.Set ||\n\t\t\t(state.type_ === ArchType.Array &&\n\t\t\t\t(state as ProxyArrayState).allIndicesReassigned_) ||\n\t\t\t(state.assigned_?.size ?? 0) > 0)\n\n\tif (shouldFinalize) {\n\t\tconst {patchPlugin_} = rootScope\n\t\tif (patchPlugin_) {\n\t\t\tconst basePath = patchPlugin_!.getPath(state)\n\n\t\t\tif (basePath) {\n\t\t\t\tpatchPlugin_!.generatePatches_(state, basePath, rootScope)\n\t\t\t}\n\t\t}\n\n\t\tmarkStateFinalized(state)\n\t}\n}\n\nexport function handleCrossReference(\n\ttarget: ImmerState,\n\tkey: string | number | symbol,\n\tvalue: any\n) {\n\tconst {scope_} = target\n\t// Check if value is a draft from this scope\n\tif (isDraft(value)) {\n\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\tif (isSameScope(state, scope_)) {\n\t\t\t// Register callback to update this location when the draft finalizes\n\n\t\t\tstate.callbacks_.push(function crossReferenceCleanup() {\n\t\t\t\t// Update the target location with finalized value\n\t\t\t\tprepareCopy(target)\n\n\t\t\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t\t\tupdateDraftInParent(target, value, finalizedValue, key)\n\t\t\t})\n\t\t}\n\t} else if (isDraftable(value)) {\n\t\t// Handle non-draft objects that might contain drafts\n\t\ttarget.callbacks_.push(function nestedDraftCleanup() {\n\t\t\tconst targetCopy = latest(target)\n\n\t\t\t// For Sets, check if value is still in the set\n\t\t\tif (target.type_ === ArchType.Set) {\n\t\t\t\tif (targetCopy.has(value)) {\n\t\t\t\t\t// Process the value to replace any nested drafts\n\t\t\t\t\thandleValue(value, scope_.handledSet_, scope_)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Maps/objects\n\t\t\t\tif (get(targetCopy, key, target.type_) === value) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tscope_.drafts_.length > 1 &&\n\t\t\t\t\t\t((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??\n\t\t\t\t\t\t\tfalse) === true &&\n\t\t\t\t\t\ttarget.copy_\n\t\t\t\t\t) {\n\t\t\t\t\t\t// This might be a non-draft value that has drafts\n\t\t\t\t\t\t// inside. We do need to recurse here to handle those.\n\t\t\t\t\t\thandleValue(\n\t\t\t\t\t\t\tget(target.copy_, key, target.type_),\n\t\t\t\t\t\t\tscope_.handledSet_,\n\t\t\t\t\t\t\tscope_\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nexport function handleValue(\n\ttarget: any,\n\thandledSet: Set<any>,\n\trootScope: ImmerScope\n) {\n\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t// This benefits especially adding large data tree's without further processing.\n\t\t// See add-data.js perf test\n\t\treturn target\n\t}\n\n\t// Skip if already handled, frozen, or not draftable\n\tif (\n\t\tisDraft(target) ||\n\t\thandledSet.has(target) ||\n\t\t!isDraftable(target) ||\n\t\tisFrozen(target)\n\t) {\n\t\treturn target\n\t}\n\n\thandledSet.add(target)\n\n\t// Process ALL properties/entries\n\teach(target, (key, value) => {\n\t\tif (isDraft(value)) {\n\t\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\t\tif (isSameScope(state, rootScope)) {\n\t\t\t\t// Replace draft with finalized value\n\n\t\t\t\tconst updatedValue = getFinalValue(state)\n\n\t\t\t\tset(target, key, updatedValue, target.type_)\n\n\t\t\t\tmarkStateFinalized(state)\n\t\t\t}\n\t\t} else if (isDraftable(value)) {\n\t\t\t// Recursively handle nested values\n\t\t\thandleValue(value, handledSet, rootScope)\n\t\t}\n\t})\n\n\treturn target\n}\n","import {\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\thandleCrossReference,\n\tWRITABLE,\n\tCONFIGURABLE,\n\tENUMERABLE,\n\tVALUE,\n\tisArray,\n\tisArrayIndex\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n\toperationMethod?: string\n\tallIndicesReassigned_?: boolean\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): [Drafted<T, ProxyState>, ProxyState] {\n\tconst baseIsArray = isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: baseIsArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\t// actually instantiated in `prepareCopy()`\n\t\tassigned_: undefined,\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false,\n\t\t// `callbacks` actually gets assigned in `createProxy`\n\t\tcallbacks_: undefined as any\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (baseIsArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn [proxy as any, state]\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tlet arrayPlugin = state.scope_.arrayMethodsPlugin_\n\t\tconst isArrayWithStringProp =\n\t\t\tstate.type_ === ArchType.Array && typeof prop === \"string\"\n\t\t// Intercept array methods so that we can override\n\t\t// behavior and skip proxy creation for perf\n\t\tif (isArrayWithStringProp) {\n\t\t\tif (arrayPlugin?.isArrayOperationMethod(prop)) {\n\t\t\t\treturn arrayPlugin.createMethodInterceptor(state, prop)\n\t\t\t}\n\t\t}\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop, state.type_)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\t// During mutating array operations, defer proxy creation for array elements\n\t\t// This optimization avoids creating unnecessary proxies during sort/reverse\n\t\tif (\n\t\t\tisArrayWithStringProp &&\n\t\t\t(state as ProxyArrayState).operationMethod &&\n\t\t\tarrayPlugin?.isMutatingArrayMethod(\n\t\t\t\t(state as ProxyArrayState).operationMethod!\n\t\t\t) &&\n\t\t\tisArrayIndex(prop)\n\t\t) {\n\t\t\t// Return raw value during mutating operations, create proxy only if modified\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\t// Ensure array keys are always numbers\n\t\t\tconst childKey = state.type_ === ArchType.Array ? +(prop as string) : prop\n\t\t\tconst childDraft = createProxy(state.scope_, value, state, childKey)\n\n\t\t\treturn (state.copy_![childKey] = childDraft)\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_!.set(prop, false)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (\n\t\t\t\tis(value, current) &&\n\t\t\t\t(value !== undefined || has(state.base_, prop, state.type_))\n\t\t\t)\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_!.set(prop, true)\n\n\t\thandleCrossReference(state, prop, value)\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\tprepareCopy(state)\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_!.set(prop, false)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tstate.assigned_!.delete(prop)\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\t[WRITABLE]: true,\n\t\t\t[CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t[VALUE]: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\n// Use `for..in` instead of `each` to work around a weird\n// prod test suite issue\nfor (let key in objectTraps) {\n\tlet fn = objectTraps[key as keyof typeof objectTraps] as Function\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\tconst args = arguments\n\t\targs[0] = args[0][0]\n\t\treturn fn.apply(this, args)\n\t}\n}\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? VALUE in desc\n\t\t\t? desc[VALUE]\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t  // prototype, we should invoke it with the draft as context!\n\t\t\t  desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: ImmerState) {\n\tif (!state.copy_) {\n\t\t// Actually create the `assigned_` map now that we\n\t\t// know this is a modified draft.\n\t\tstate.assigned_ = new Map()\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent,\n\tImmerScope,\n\tregisterChildFinalizationCallback,\n\tArchType,\n\tMapSetPlugin,\n\tAnyMap,\n\tAnySet,\n\tisObjectish,\n\tisFunction,\n\tisBoolean,\n\tPluginMapSet,\n\tPluginPatches\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\"\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\tuseStrictIteration_: boolean = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t\tuseStrictIteration?: boolean\n\t}) {\n\t\tif (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)\n\t\tif (isBoolean(config?.useStrictShallowCopy))\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t\tif (isBoolean(config?.useStrictIteration))\n\t\t\tthis.setUseStrictIteration(config!.useStrictIteration)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (isFunction(base) && !isFunction(recipe)) {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (!isFunction(recipe)) die(6)\n\t\tif (patchListener !== undefined && !isFunction(patchListener)) die(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(scope, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || !isObjectish(base)) {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n\t\t\t\t\tpatches_: p,\n\t\t\t\t\tinversePatches_: ip\n\t\t\t\t} as ImmerScope) // dummy scope\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (isFunction(base)) {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(scope, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\t/**\n\t * Pass false to use faster iteration that skips non-enumerable properties\n\t * but still handles symbols for compatibility.\n\t *\n\t * By default, strict iteration is enabled (includes all own properties).\n\t */\n\tsetUseStrictIteration(value: boolean) {\n\t\tthis.useStrictIteration_ = value\n\t}\n\n\tshouldUseStrictIteration(): boolean {\n\t\treturn this.useStrictIteration_\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(PluginPatches).applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\trootScope: ImmerScope,\n\tvalue: T,\n\tparent?: ImmerState,\n\tkey?: string | number | symbol\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\t// returning a tuple here lets us skip a proxy access\n\t// to DRAFT_STATE later\n\tconst [draft, state] = isMap(value)\n\t\t? getPlugin(PluginMapSet).proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(PluginMapSet).proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent?.scope_ ?? getCurrentScope()\n\tscope.drafts_.push(draft)\n\n\t// Ensure the parent callbacks are passed down so we actually\n\t// track all callbacks added throughout the tree\n\tstate.callbacks_ = parent?.callbacks_ ?? []\n\tstate.key_ = key\n\n\tif (parent && key !== undefined) {\n\t\tregisterChildFinalizationCallback(parent, state, key)\n\t} else {\n\t\t// It's a root draft, register it with the scope\n\t\tstate.callbacks_.push(function rootDraftCleanup(rootScope) {\n\t\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\t\tconst {patchPlugin_} = rootScope\n\n\t\t\tif (state.modified_ && patchPlugin_) {\n\t\t\t\tpatchPlugin_.generatePatches_(state, [], rootScope)\n\t\t\t}\n\t\t})\n\t}\n\n\treturn draft as any\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tlet strict = true // Default to strict for compatibility\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t\tstrict = state.scope_.immer_.shouldUseStrictIteration()\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(\n\t\tcopy,\n\t\t(key, childValue) => {\n\t\t\tset(copy, key, currentImpl(childValue))\n\t\t},\n\t\tstrict\n\t)\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors,\n\tDRAFT_STATE,\n\tgetProxyDraft,\n\tImmerScope,\n\tisObjectish,\n\tisFunction,\n\tCONSTRUCTOR,\n\tPluginPatches,\n\tisArray,\n\tPROTOTYPE\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tfunction getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {\n\t\t// Step 1: Check if state has a stored key\n\t\tif (state.key_ !== undefined) {\n\t\t\t// Step 2: Validate the key is still valid in parent\n\n\t\t\tconst parentCopy = state.parent_!.copy_ ?? state.parent_!.base_\n\t\t\tconst proxyDraft = getProxyDraft(get(parentCopy, state.key_!))\n\t\t\tconst valueAtKey = get(parentCopy, state.key_!)\n\n\t\t\tif (valueAtKey === undefined) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Check if the value at the key is still related to this draft\n\t\t\t// It should be either the draft itself, the base, or the copy\n\t\t\tif (\n\t\t\t\tvalueAtKey !== state.draft_ &&\n\t\t\t\tvalueAtKey !== state.base_ &&\n\t\t\t\tvalueAtKey !== state.copy_\n\t\t\t) {\n\t\t\t\treturn null // Value was replaced with something else\n\t\t\t}\n\t\t\tif (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n\t\t\t\treturn null // Different draft\n\t\t\t}\n\n\t\t\t// Step 3: Handle Set case specially\n\t\t\tconst isSet = state.parent_!.type_ === ArchType.Set\n\t\t\tlet key: string | number\n\n\t\t\tif (isSet) {\n\t\t\t\t// For Sets, find the index in the drafts_ map\n\t\t\t\tconst setParent = state.parent_ as SetState\n\t\t\t\tkey = Array.from(setParent.drafts_.keys()).indexOf(state.key_)\n\t\t\t} else {\n\t\t\t\tkey = state.key_ as string | number\n\t\t\t}\n\n\t\t\t// Step 4: Validate key still exists in parent\n\t\t\tif (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {\n\t\t\t\treturn null // Key deleted\n\t\t\t}\n\n\t\t\t// Step 5: Add key to path\n\t\t\tpath.push(key)\n\t\t}\n\n\t\t// Step 6: Recurse to parent if exists\n\t\tif (state.parent_) {\n\t\t\treturn getPath(state.parent_, path)\n\t\t}\n\n\t\t// Step 7: At root - reverse path and validate\n\t\tpath.reverse()\n\n\t\ttry {\n\t\t\t// Validate path can be resolved from ROOT\n\t\t\tresolvePath(state.copy_, path)\n\t\t} catch (e) {\n\t\t\treturn null // Path invalid\n\t\t}\n\n\t\treturn path\n\t}\n\n\t// NEW: Add resolvePath helper function\n\tfunction resolvePath(base: any, path: PatchPath): any {\n\t\tlet current = base\n\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\tconst key = path[i]\n\t\t\tcurrent = get(current, key)\n\t\t\tif (!isObjectish(current) || current === null) {\n\t\t\t\tthrow new Error(`Cannot resolve path at '${path.join(\"/\")}'`)\n\t\t\t}\n\t\t}\n\t\treturn current\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tscope: ImmerScope\n\t): void {\n\t\tif (state.scope_.processedForPatches_.has(state)) {\n\t\t\treturn\n\t\t}\n\n\t\tstate.scope_.processedForPatches_.add(state)\n\n\t\tconst {patches_, inversePatches_} = scope\n\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\tconst allReassigned = state.allIndicesReassigned_ === true\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tconst copiedItem = copy_[i]\n\t\t\tconst baseItem = base_[i]\n\n\t\t\tconst isAssigned = allReassigned || assigned_?.get(i.toString())\n\t\t\tif (isAssigned && copiedItem !== baseItem) {\n\t\t\t\tconst childState = copiedItem?.[DRAFT_STATE]\n\t\t\t\tif (childState && childState.modified_) {\n\t\t\t\t\t// Skip - let the child generate its own patches\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copiedItem)\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(baseItem)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_, type_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key, type_)\n\t\t\tconst value = get(copy_!, key, type_)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(\n\t\t\t\top === REMOVE\n\t\t\t\t\t? {op, path}\n\t\t\t\t\t: {op, path, value: clonePatchValueIfNeeded(value)}\n\t\t\t)\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tscope: ImmerScope\n\t): void {\n\t\tconst {patches_, inversePatches_} = scope\n\t\tpatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === CONSTRUCTOR)\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (!isObjectish(base)) die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(PluginPatches, {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_,\n\t\tgetPath\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach,\n\tgetValue,\n\tPluginMapSet,\n\thandleCrossReference\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\thandleCrossReference(state, key, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_, value, state, key)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, MapState] {\n\t\t// @ts-ignore\n\t\tconst map = new DraftMap(target, parent)\n\t\treturn [map as any, map[DRAFT_STATE]]\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t\thandleCrossReference(state, value, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, SetState] {\n\t\t// @ts-ignore\n\t\tconst set = new DraftSet(target, parent)\n\t\treturn [set as any, set[DRAFT_STATE]]\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_, value, state, value)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tfunction fixSetContents(target: ImmerState) {\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\tif (target.type_ === ArchType.Set && target.copy_) {\n\t\t\tconst copy = new Set(target.copy_)\n\t\t\ttarget.copy_.clear()\n\t\t\tcopy.forEach(value => {\n\t\t\t\ttarget.copy_!.add(getValue(value))\n\t\t\t})\n\t\t}\n\t}\n\n\tloadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})\n}\n","import {\n\tPluginArrayMethods,\n\tlatest,\n\tloadPlugin,\n\tmarkChanged,\n\tprepareCopy,\n\tProxyArrayState\n} from \"../internal\"\n\n/**\n * Methods that directly modify the array in place.\n * These operate on the copy without creating per-element proxies:\n * - `push`, `pop`: Add/remove from end\n * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)\n * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)\n * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)\n */\ntype MutatingArrayMethod =\n\t| \"push\"\n\t| \"pop\"\n\t| \"shift\"\n\t| \"unshift\"\n\t| \"splice\"\n\t| \"reverse\"\n\t| \"sort\"\n\n/**\n * Methods that read from the array without modifying it.\n * These fall into distinct categories based on return semantics:\n *\n * **Subset operations** (return drafts - mutations propagate):\n * - `filter`, `slice`: Return array of draft proxies\n * - `find`, `findLast`: Return single draft proxy or undefined\n *\n * **Transform operations** (return base values - mutations don't track):\n * - `concat`, `flat`: Create new structures, not subsets of original\n *\n * **Primitive-returning** (no draft needed):\n * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers\n * - `some`, `every`, `includes`: Return booleans\n * - `join`, `toString`, `toLocaleString`: Return strings\n */\ntype NonMutatingArrayMethod =\n\t| \"filter\"\n\t| \"slice\"\n\t| \"concat\"\n\t| \"flat\"\n\t| \"find\"\n\t| \"findIndex\"\n\t| \"findLast\"\n\t| \"findLastIndex\"\n\t| \"some\"\n\t| \"every\"\n\t| \"indexOf\"\n\t| \"lastIndexOf\"\n\t| \"includes\"\n\t| \"join\"\n\t| \"toString\"\n\t| \"toLocaleString\"\n\n/** Union of all array operation methods handled by the plugin. */\nexport type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod\n\n/**\n * Enables optimized array method handling for Immer drafts.\n *\n * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,\n * significantly improving performance for array-heavy operations.\n *\n * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):\n * Operate directly on the copy without creating per-element proxies.\n *\n * **Non-mutating methods** fall into categories:\n * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track\n * - **Transform operations** (concat, flat): Return base values - mutations don't track\n * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives\n *\n * **Important**: Callbacks for overridden methods receive base values, not drafts.\n * This is the core performance optimization.\n *\n * @example\n * ```ts\n * import { enableArrayMethods, produce } from \"immer\"\n *\n * enableArrayMethods()\n *\n * const next = produce(state, draft => {\n *   // Optimized - no proxy creation per element\n *   draft.items.sort((a, b) => a.value - b.value)\n *\n *   // filter returns drafts - mutations propagate\n *   const filtered = draft.items.filter(x => x.value > 5)\n *   filtered[0].value = 999 // Affects draft.items[originalIndex]\n * })\n * ```\n *\n * @see https://immerjs.github.io/immer/array-methods\n */\nexport function enableArrayMethods() {\n\tconst SHIFTING_METHODS = new Set<MutatingArrayMethod>([\"shift\", \"unshift\"])\n\n\tconst QUEUE_METHODS = new Set<MutatingArrayMethod>([\"push\", \"pop\"])\n\n\tconst RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...QUEUE_METHODS,\n\t\t...SHIFTING_METHODS\n\t])\n\n\tconst REORDERING_METHODS = new Set<MutatingArrayMethod>([\"reverse\", \"sort\"])\n\n\t// Optimized method detection using array-based lookup\n\tconst MUTATING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...RESULT_RETURNING_METHODS,\n\t\t...REORDERING_METHODS,\n\t\t\"splice\"\n\t])\n\n\tconst FIND_METHODS = new Set<NonMutatingArrayMethod>([\"find\", \"findLast\"])\n\n\tconst NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([\n\t\t\"filter\",\n\t\t\"slice\",\n\t\t\"concat\",\n\t\t\"flat\",\n\t\t...FIND_METHODS,\n\t\t\"findIndex\",\n\t\t\"findLastIndex\",\n\t\t\"some\",\n\t\t\"every\",\n\t\t\"indexOf\",\n\t\t\"lastIndexOf\",\n\t\t\"includes\",\n\t\t\"join\",\n\t\t\"toString\",\n\t\t\"toLocaleString\"\n\t])\n\n\t// Type guard for method detection\n\tfunction isMutatingArrayMethod(\n\t\tmethod: string\n\t): method is MutatingArrayMethod {\n\t\treturn MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isNonMutatingArrayMethod(\n\t\tmethod: string\n\t): method is NonMutatingArrayMethod {\n\t\treturn NON_MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isArrayOperationMethod(\n\t\tmethod: string\n\t): method is ArrayOperationMethod {\n\t\treturn isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)\n\t}\n\n\tfunction enterOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: ArrayOperationMethod\n\t) {\n\t\tstate.operationMethod = method\n\t}\n\n\tfunction exitOperation(state: ProxyArrayState) {\n\t\tstate.operationMethod = undefined\n\t}\n\n\t// Shared utility functions for array method handlers\n\tfunction executeArrayMethod<T>(\n\t\tstate: ProxyArrayState,\n\t\toperation: () => T,\n\t\tmarkLength = true\n\t): T {\n\t\tprepareCopy(state)\n\t\tconst result = operation()\n\t\tmarkChanged(state)\n\t\tif (markLength) state.assigned_!.set(\"length\", true)\n\t\treturn result\n\t}\n\n\tfunction markAllIndicesReassigned(state: ProxyArrayState) {\n\t\tstate.allIndicesReassigned_ = true\n\t}\n\n\tfunction normalizeSliceIndex(index: number, length: number): number {\n\t\tif (index < 0) {\n\t\t\treturn Math.max(length + index, 0)\n\t\t}\n\t\treturn Math.min(index, length)\n\t}\n\n\t/**\n\t * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).\n\t *\n\t * Operates directly on `state.copy_` without creating per-element proxies.\n\t * For shifting methods (shift, unshift), marks all indices as reassigned since\n\t * indices shift.\n\t *\n\t * @returns For push/pop/shift/unshift: the native method result. For others: the draft.\n\t */\n\tfunction handleSimpleOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(state, () => {\n\t\t\tconst result = (state.copy_! as any)[method](...args)\n\n\t\t\t// Handle index reassignment for shifting methods\n\t\t\tif (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t}\n\n\t\t\t// Return appropriate value based on method\n\t\t\treturn RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)\n\t\t\t\t? result\n\t\t\t\t: state.draft_\n\t\t})\n\t}\n\n\t/**\n\t * Handles reordering operations (reverse, sort) that change element order.\n\t *\n\t * Operates directly on `state.copy_` and marks all indices as reassigned\n\t * since element positions change. Does not mark length as changed since\n\t * these operations preserve array length.\n\t *\n\t * @returns The draft proxy for method chaining.\n\t */\n\tfunction handleReorderingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(\n\t\t\tstate,\n\t\t\t() => {\n\t\t\t\t;(state.copy_! as any)[method](...args)\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\treturn state.draft_\n\t\t\t},\n\t\t\tfalse\n\t\t) // Don't mark length as changed\n\t}\n\n\t/**\n\t * Creates an interceptor function for a specific array method.\n\t *\n\t * The interceptor wraps array method calls to:\n\t * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap\n\t *    to detect we're inside an optimized method and skip proxy creation)\n\t * 2. Route to appropriate handler based on method type\n\t * 3. Clean up the operation flag in `finally` block\n\t *\n\t * The `operationMethod` flag is the key mechanism that enables the proxy's `get`\n\t * trap to return base values instead of creating nested proxies during iteration.\n\t *\n\t * @param state - The proxy array state\n\t * @param originalMethod - Name of the array method being intercepted\n\t * @returns Interceptor function that handles the method call\n\t */\n\tfunction createMethodInterceptor(\n\t\tstate: ProxyArrayState,\n\t\toriginalMethod: string\n\t) {\n\t\treturn function interceptedMethod(...args: any[]) {\n\t\t\t// Enter operation mode - this flag tells the proxy's get trap to return\n\t\t\t// base values instead of creating nested proxies during iteration\n\t\t\tconst method = originalMethod as ArrayOperationMethod\n\t\t\tenterOperation(state, method)\n\n\t\t\ttry {\n\t\t\t\t// Check if this is a mutating method\n\t\t\t\tif (isMutatingArrayMethod(method)) {\n\t\t\t\t\t// Direct method dispatch - no configuration lookup needed\n\t\t\t\t\tif (RESULT_RETURNING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleSimpleOperation(state, method, args)\n\t\t\t\t\t}\n\t\t\t\t\tif (REORDERING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleReorderingOperation(state, method, args)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === \"splice\") {\n\t\t\t\t\t\tconst res = executeArrayMethod(state, () =>\n\t\t\t\t\t\t\tstate.copy_!.splice(...(args as [number, number, ...any[]]))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\t\t\treturn res\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle non-mutating methods\n\t\t\t\t\treturn handleNonMutatingOperation(state, method, args)\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// Always exit operation mode - must be in finally to handle exceptions\n\t\t\t\texitOperation(state)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Handles non-mutating array methods with different return semantics.\n\t *\n\t * **Subset operations** return draft proxies for mutation tracking:\n\t * - `filter`, `slice`: Return `state.draft_[i]` for each selected element\n\t * - `find`, `findLast`: Return `state.draft_[i]` for the found element\n\t *\n\t * This allows mutations on returned elements to propagate back to the draft:\n\t * ```ts\n\t * const filtered = draft.items.filter(x => x.value > 5)\n\t * filtered[0].value = 999 // Mutates draft.items[originalIndex]\n\t * ```\n\t *\n\t * **Transform operations** return base values (no draft tracking):\n\t * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.\n\t *   Since the result structure differs from the original, tracking mutations\n\t *   back to specific draft indices would be impractical/impossible.\n\t *\n\t * **Primitive operations** return the native result directly:\n\t * - `indexOf`, `includes`, `some`, `every`, `join`, etc.\n\t *\n\t * @param state - The proxy array state\n\t * @param method - The non-mutating method name\n\t * @param args - Arguments passed to the method\n\t * @returns Drafts for subset operations, base values for transforms, primitives otherwise\n\t */\n\tfunction handleNonMutatingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: NonMutatingArrayMethod,\n\t\targs: any[]\n\t) {\n\t\tconst source = latest(state)\n\n\t\t// Methods that return arrays with selected items - need to return drafts\n\t\tif (method === \"filter\") {\n\t\t\tconst predicate = args[0]\n\t\t\tconst result: any[] = []\n\n\t\t\t// First pass: call predicate on base values to determine which items pass\n\t\t\tfor (let i = 0; i < source.length; i++) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\t// Only create draft for items that passed the predicate\n\t\t\t\t\tresult.push(state.draft_[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\tif (FIND_METHODS.has(method)) {\n\t\t\tconst predicate = args[0]\n\t\t\tconst isForward = method === \"find\"\n\t\t\tconst step = isForward ? 1 : -1\n\t\t\tconst start = isForward ? 0 : source.length - 1\n\n\t\t\tfor (let i = start; i >= 0 && i < source.length; i += step) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\treturn state.draft_[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (method === \"slice\") {\n\t\t\tconst rawStart = args[0] ?? 0\n\t\t\tconst rawEnd = args[1] ?? source.length\n\n\t\t\t// Normalize negative indices\n\t\t\tconst start = normalizeSliceIndex(rawStart, source.length)\n\t\t\tconst end = normalizeSliceIndex(rawEnd, source.length)\n\n\t\t\tconst result: any[] = []\n\n\t\t\t// Return drafts for items in the slice range\n\t\t\tfor (let i = start; i < end; i++) {\n\t\t\t\tresult.push(state.draft_[i])\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\t// For other methods, call on base array directly:\n\t\t// - indexOf, includes, join, toString: Return primitives, no draft needed\n\t\t// - concat, flat: Return NEW arrays (not subsets). Elements are base values.\n\t\t//   This is intentional - concat/flat create new data structures rather than\n\t\t//   selecting subsets of the original, making draft tracking impractical.\n\t\treturn source[method as keyof typeof Array.prototype](...args)\n\t}\n\n\tloadPlugin(PluginArrayMethods, {\n\t\tcreateMethodInterceptor,\n\t\tisArrayOperationMethod,\n\t\tisMutatingArrayMethod\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,eAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,UAAyB,OAAO,IAAI,eAAe;AAUzD,IAAM,YAA2B,OAAO,IAAI,iBAAiB;AAE7D,IAAM,cAA6B,OAAO,IAAI,aAAa;;;ACf3D,IAAM,SACZ,QAAQ,IAAI,aAAa,eACtB;AAAA;AAAA,EAEA,SAAS,QAAgB;AACxB,WAAO,mBAAmB,yFAAyF;AAAA,EACpH;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,sJAAsJ;AAAA,EAC9J;AAAA,EACA;AAAA,EACA,SAAS,MAAW;AACnB,WACC,yHACA;AAAA,EAEF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,mCAAmC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,oCAAoC;AAAA,EAC5C;AAAA;AAAA;AAGA,IACA,CAAC;AAEE,SAAS,IAAI,UAAkB,MAAoB;AACzD,MAAI,QAAQ,IAAI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AO3C,IAAI,gBAAgB,CAAI,UAA2B;","names":["Immer","immer","current","Immer","base","rootScope","isSet","current","set","Immer"]}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.production.js
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.production.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.production.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+"use strict";var _e=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(e,t)=>{for(var r in t)_e(e,r,{get:t[r],enumerable:!0})},rt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ze(t))!et.call(e,o)&&o!==r&&_e(e,o,{get:()=>t[o],enumerable:!(n=Xe(t,o))||n.enumerable});return e};var nt=e=>rt(_e({},"__esModule",{value:!0}),e);var At={};tt(At,{Immer:()=>me,applyPatches:()=>mt,castDraft:()=>gt,castImmutable:()=>xt,createDraft:()=>St,current:()=>Oe,enableArrayMethods:()=>Qe,enableMapSet:()=>Je,enablePatches:()=>Ye,finishDraft:()=>Pt,freeze:()=>J,immerable:()=>j,isDraft:()=>w,isDraftable:()=>D,nothing:()=>K,original:()=>Ue,produce:()=>lt,produceWithPatches:()=>yt,setAutoFreeze:()=>dt,setUseStrictIteration:()=>ht,setUseStrictShallowCopy:()=>pt});module.exports=nt(At);var K=Symbol.for("immer-nothing"),j=Symbol.for("immer-draftable"),y=Symbol.for("immer-state");function b(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var C=Object,L=C.getPrototypeOf,te="constructor",re="prototype",Pe="configurable",ce="enumerable",se="writable",ne="value",w=e=>!!e&&!!e[y];function D(e){return e?ke(e)||$(e)||!!e[j]||!!e[te]?.[j]||q(e)||Y(e):!1}var at=C[re][te].toString(),ze=new WeakMap;function ke(e){if(!e||!W(e))return!1;let t=L(e);if(t===null||t===C[re])return!0;let r=C.hasOwnProperty.call(t,te)&&t[te];if(r===Object)return!0;if(!V(r))return!1;let n=ze.get(r);return n===void 0&&(n=Function.toString.call(r),ze.set(r,n)),n===at}function Ue(e){return w(e)||b(15,e),e[y].t}function U(e,t,r=!0){H(e)===0?(r?Reflect.ownKeys(e):C.keys(e)).forEach(o=>{t(o,e[o],e)}):e.forEach((n,o)=>t(o,n,e))}function H(e){let t=e[y];return t?t.r:$(e)?1:q(e)?2:Y(e)?3:0}var G=(e,t,r=H(e))=>r===2?e.has(t):C[re].hasOwnProperty.call(e,t),k=(e,t,r=H(e))=>r===2?e.get(t):e[t],ae=(e,t,r,n=H(e))=>{n===2?e.set(t,r):n===3?e.add(r):e[t]=r};function je(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}var $=Array.isArray,q=e=>e instanceof Map,Y=e=>e instanceof Set,W=e=>typeof e=="object",V=e=>typeof e=="function",ge=e=>typeof e=="boolean";function Le(e){let t=+e;return Number.isInteger(t)&&String(t)===e}var Ee=e=>W(e)?e?.[y]:null,O=e=>e.e||e.t,Ve=e=>{let t=Ee(e);return t?t.e??t.t:e},xe=e=>e.s?e.e:e.t;function fe(e,t){if(q(e))return new Map(e);if(Y(e))return new Set(e);if($(e))return Array[re].slice.call(e);let r=ke(e);if(t===!0||t==="class_only"&&!r){let n=C.getOwnPropertyDescriptors(e);delete n[y];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let d=o[i],S=n[d];S[se]===!1&&(S[se]=!0,S[Pe]=!0),(S.get||S.set)&&(n[d]={[Pe]:!0,[se]:!0,[ce]:S[ce],[ne]:e[d]})}return C.create(L(e),n)}else{let n=L(e);if(n!==null&&r)return{...e};let o=C.create(n);return C.assign(o,e)}}function J(e,t=!1){return oe(e)||w(e)||!D(e)||(H(e)>1&&C.defineProperties(e,{set:Se,add:Se,clear:Se,delete:Se}),C.freeze(e),t&&U(e,(r,n)=>{J(n,!0)},!1)),e}function ot(){b(2)}var Se={[ne]:ot};function oe(e){return e===null||!W(e)?!0:C.isFrozen(e)}var v="MapSet",Q="Patches",le="ArrayMethods",Ae={};function B(e){let t=Ae[e];return t||b(0,e),t}var we=e=>!!Ae[e];function ie(e,t){Ae[e]||(Ae[e]=t)}var ye,X=()=>ye,it=(e,t)=>({o:[],i:e,l:t,F:!0,m:0,P:new Set,T:new Set,I:we(v)?B(v):void 0,E:we(le)?B(le):void 0});function Fe(e,t){t&&(e.x=B(Q),e.p=[],e.d=[],e.C=t)}function de(e){Ie(e),e.o.forEach(st),e.o=null}function Ie(e){e===ye&&(ye=e.i)}var Ce=e=>ye=it(ye,e);function st(e){let t=e[y];t.r===0||t.r===1?t.b():t.g=!0}function Ne(e,t){t.m=t.o.length;let r=t.o[0];if(e!==void 0&&e!==r){r[y].s&&(de(t),b(4)),D(e)&&(e=Be(t,e));let{x:o}=t;o&&o.M(r[y].t,e,t)}else e=Be(t,r);return ct(t,e,!0),de(t),t.p&&t.C(t.p,t.d),e!==K?e:void 0}function Be(e,t){if(oe(t))return t;let r=t[y];if(!r)return Me(t,e.P,e);if(!Te(r,e))return t;if(!r.s)return r.t;if(!r.u){let{f:n}=r;if(n)for(;n.length>0;)n.pop()(e);ve(r,e)}return r.e}function ct(e,t,r=!1){!e.i&&e.l.h&&e.F&&J(t,r)}function Ke(e){e.u=!0,e.n.m--}var Te=(e,t)=>e.n===t,ut=[];function He(e,t,r,n){let o=O(e),i=e.r;if(n!==void 0&&k(o,n,i)===t){ae(o,n,r,i);return}if(!e.D){let S=e.D=new Map;U(o,(p,M)=>{if(w(M)){let a=S.get(M)||[];a.push(p),S.set(M,a)}})}let d=e.D.get(t)??ut;for(let S of d)ae(o,S,r,i)}function We(e,t,r){e.f.push(function(o){let i=t;if(!i||!Te(i,o))return;o.I?.fixSetContents(i);let d=xe(i);He(e,i.c??i,d,r),ve(i,o)})}function ve(e,t){if(e.s&&!e.u&&(e.r===3||e.r===1&&e.R||(e.a?.size??0)>0)){let{x:n}=t;if(n){let o=n.getPath(e);o&&n.O(e,o,t)}Ke(e)}}function pe(e,t,r){let{n}=e;if(w(r)){let o=r[y];Te(o,n)&&o.f.push(function(){Z(e);let d=xe(o);He(e,r,d,t)})}else D(r)&&e.f.push(function(){let i=O(e);e.r===3?i.has(r)&&Me(r,n.P,n):k(i,t,e.r)===r&&n.o.length>1&&(e.a.get(t)??!1)===!0&&e.e&&Me(k(e.e,t,e.r),n.P,n)})}function Me(e,t,r){return!r.l.h&&r.m<1||w(e)||t.has(e)||!D(e)||oe(e)||(t.add(e),U(e,(n,o)=>{if(w(o)){let i=o[y];if(Te(i,r)){let d=xe(i);ae(e,n,d,e.r),Ke(i)}}else D(o)&&Me(o,t,r)})),e}function Ge(e,t){let r=$(e),n={r:r?1:0,n:t?t.n:X(),s:!1,u:!1,a:void 0,i:t,t:e,c:null,e:null,b:null,S:!1,f:void 0},o=n,i=be;r&&(o=[n],i=he);let{revoke:d,proxy:S}=Proxy.revocable(o,i);return n.c=S,n.b=d,[S,n]}var be={get(e,t){if(t===y)return e;let r=e.n.E,n=e.r===1&&typeof t=="string";if(n&&r?.isArrayOperationMethod(t))return r.createMethodInterceptor(e,t);let o=O(e);if(!G(o,t,e.r))return ft(e,o,t);let i=o[t];if(e.u||!D(i)||n&&e.operationMethod&&r?.isMutatingArrayMethod(e.operationMethod)&&Le(t))return i;if(i===Re(e.t,t)){Z(e);let d=e.r===1?+t:t,S=ee(e.n,i,e,d);return e.e[d]=S}return i},has(e,t){return t in O(e)},ownKeys(e){return Reflect.ownKeys(O(e))},set(e,t,r){let n=$e(O(e),t);if(n?.set)return n.set.call(e.c,r),!0;if(!e.s){let o=Re(O(e),t),i=o?.[y];if(i&&i.t===r)return e.e[t]=r,e.a.set(t,!1),!0;if(je(r,o)&&(r!==void 0||G(e.t,t,e.r)))return!0;Z(e),z(e)}return e.e[t]===r&&(r!==void 0||t in e.e)||Number.isNaN(r)&&Number.isNaN(e.e[t])||(e.e[t]=r,e.a.set(t,!0),pe(e,t,r)),!0},deleteProperty(e,t){return Z(e),Re(e.t,t)!==void 0||t in e.t?(e.a.set(t,!1),z(e)):e.a.delete(t),e.e&&delete e.e[t],!0},getOwnPropertyDescriptor(e,t){let r=O(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{[se]:!0,[Pe]:e.r!==1||t!=="length",[ce]:n[ce],[ne]:r[t]}},defineProperty(){b(11)},getPrototypeOf(e){return L(e.t)},setPrototypeOf(){b(12)}},he={};for(let e in be){let t=be[e];he[e]=function(){let r=arguments;return r[0]=r[0][0],t.apply(this,r)}}he.deleteProperty=function(e,t){return he.set.call(this,e,t,void 0)};he.set=function(e,t,r){return be.set.call(this,e[0],t,r,e[0])};function Re(e,t){let r=e[y];return(r?O(r):e)[t]}function ft(e,t,r){let n=$e(t,r);return n?ne in n?n[ne]:n.get?.call(e.c):void 0}function $e(e,t){if(!(t in e))return;let r=L(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=L(r)}}function z(e){e.s||(e.s=!0,e.i&&z(e.i))}function Z(e){e.e||(e.a=new Map,e.e=fe(e.t,e.n.l.A))}var me=class{constructor(t){this.h=!0;this.A=!1;this._=!1;this.produce=(t,r,n)=>{if(V(t)&&!V(r)){let i=r;r=t;let d=this;return function(p=i,...M){return d.produce(p,a=>r.call(this,a,...M))}}V(r)||b(6),n!==void 0&&!V(n)&&b(7);let o;if(D(t)){let i=Ce(this),d=ee(i,t,void 0),S=!0;try{o=r(d),S=!1}finally{S?de(i):Ie(i)}return Fe(i,n),Ne(o,i)}else if(!t||!W(t)){if(o=r(t),o===void 0&&(o=t),o===K&&(o=void 0),this.h&&J(o,!0),n){let i=[],d=[];B(Q).M(t,o,{p:i,d}),n(i,d)}return o}else b(1,t)};this.produceWithPatches=(t,r)=>{if(V(t))return(d,...S)=>this.produceWithPatches(d,p=>t(p,...S));let n,o;return[this.produce(t,r,(d,S)=>{n=d,o=S}),n,o]};ge(t?.autoFreeze)&&this.setAutoFreeze(t.autoFreeze),ge(t?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),ge(t?.useStrictIteration)&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){D(t)||b(8),w(t)&&(t=Oe(t));let r=Ce(this),n=ee(r,t,void 0);return n[y].S=!0,Ie(r),n}finishDraft(t,r){let n=t&&t[y];(!n||!n.S)&&b(9);let{n:o}=n;return Fe(o,r),Ne(void 0,o)}setAutoFreeze(t){this.h=t}setUseStrictShallowCopy(t){this.A=t}setUseStrictIteration(t){this._=t}shouldUseStrictIteration(){return this._}applyPatches(t,r){let n;for(n=r.length-1;n>=0;n--){let i=r[n];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}n>-1&&(r=r.slice(n+1));let o=B(Q).N;return w(t)?o(t,r):this.produce(t,i=>o(i,r))}};function ee(e,t,r,n){let[o,i]=q(t)?B(v).w(t,r):Y(t)?B(v).V(t,r):Ge(t,r);return(r?.n??X()).o.push(o),i.f=r?.f??[],i.y=n,r&&n!==void 0?We(r,i,n):i.f.push(function(p){p.I?.fixSetContents(i);let{x:M}=p;i.s&&M&&M.O(i,[],p)}),o}function Oe(e){return w(e)||b(10,e),qe(e)}function qe(e){if(!D(e)||oe(e))return e;let t=e[y],r,n=!0;if(t){if(!t.s)return t.t;t.u=!0,r=fe(e,t.n.l.A),n=t.n.l.shouldUseStrictIteration()}else r=fe(e,!0);return U(r,(o,i)=>{ae(r,o,qe(i))},n),t&&(t.u=!1),r}function Ye(){function t(u,g=[]){if(u.y!==void 0){let m=u.i.e??u.i.t,x=Ee(k(m,u.y)),A=k(m,u.y);if(A===void 0||A!==u.c&&A!==u.t&&A!==u.e||x!=null&&x.t!==u.t)return null;let s=u.i.r===3,l;if(s){let h=u.i;l=Array.from(h.o.keys()).indexOf(u.y)}else l=u.y;if(!(s&&m.size>l||G(m,l)))return null;g.push(l)}if(u.i)return t(u.i,g);g.reverse();try{r(u.e,g)}catch{return null}return g}function r(u,g){let m=u;for(let x=0;x<g.length-1;x++){let A=g[x];if(m=k(m,A),!W(m)||m===null)throw new Error(`Cannot resolve path at '${g.join("/")}'`)}return m}let n="replace",o="add",i="remove";function d(u,g,m){if(u.n.T.has(u))return;u.n.T.add(u);let{p:x,d:A}=m;switch(u.r){case 0:case 2:return p(u,g,x,A);case 1:return S(u,g,x,A);case 3:return M(u,g,x,A)}}function S(u,g,m,x){let{t:A,a:s}=u,l=u.e;l.length<A.length&&([A,l]=[l,A],[m,x]=[x,m]);let h=u.R===!0;for(let f=0;f<A.length;f++){let I=l[f],E=A[f];if((h||s?.get(f.toString()))&&I!==E){let N=I?.[y];if(N&&N.s)continue;let R=g.concat([f]);m.push({op:n,path:R,value:_(I)}),x.push({op:n,path:R,value:_(E)})}}for(let f=A.length;f<l.length;f++){let I=g.concat([f]);m.push({op:o,path:I,value:_(l[f])})}for(let f=l.length-1;A.length<=f;--f){let I=g.concat([f]);x.push({op:i,path:I})}}function p(u,g,m,x){let{t:A,e:s,r:l}=u;U(u.a,(h,f)=>{let I=k(A,h,l),E=k(s,h,l),T=f?G(A,h)?n:o:i;if(I===E&&T===n)return;let N=g.concat(h);m.push(T===i?{op:T,path:N}:{op:T,path:N,value:_(E)}),x.push(T===o?{op:i,path:N}:T===i?{op:o,path:N,value:_(I)}:{op:n,path:N,value:_(I)})})}function M(u,g,m,x){let{t:A,e:s}=u,l=0;A.forEach(h=>{if(!s.has(h)){let f=g.concat([l]);m.push({op:i,path:f,value:h}),x.unshift({op:o,path:f,value:h})}l++}),l=0,s.forEach(h=>{if(!A.has(h)){let f=g.concat([l]);m.push({op:o,path:f,value:h}),x.unshift({op:i,path:f,value:h})}l++})}function a(u,g,m){let{p:x,d:A}=m;x.push({op:n,path:[],value:g===K?void 0:g}),A.push({op:n,path:[],value:u})}function c(u,g){return g.forEach(m=>{let{path:x,op:A}=m,s=u;for(let I=0;I<x.length-1;I++){let E=H(s),T=x[I];typeof T!="string"&&typeof T!="number"&&(T=""+T),(E===0||E===1)&&(T==="__proto__"||T===te)&&b(16+3),V(s)&&T===re&&b(16+3),s=k(s,T),W(s)||b(16+2,x.join("/"))}let l=H(s),h=P(m.value),f=x[x.length-1];switch(A){case n:switch(l){case 2:return s.set(f,h);case 3:b(16);default:return s[f]=h}case o:switch(l){case 1:return f==="-"?s.push(h):s.splice(f,0,h);case 2:return s.set(f,h);case 3:return s.add(h);default:return s[f]=h}case i:switch(l){case 1:return s.splice(f,1);case 2:return s.delete(f);case 3:return s.delete(m.value);default:return delete s[f]}default:b(16+1,A)}}),u}function P(u){if(!D(u))return u;if($(u))return u.map(P);if(q(u))return new Map(Array.from(u.entries()).map(([m,x])=>[m,P(x)]));if(Y(u))return new Set(Array.from(u).map(P));let g=Object.create(L(u));for(let m in u)g[m]=P(u[m]);return G(u,j)&&(g[j]=u[j]),g}function _(u){return w(u)?P(u):u}ie(Q,{N:c,O:d,M:a,getPath:t})}function Je(){class e extends Map{constructor(a,c){super();this[y]={r:2,i:c,n:c?c.n:X(),s:!1,u:!1,e:void 0,a:void 0,t:a,c:this,S:!1,g:!1,f:[]}}get size(){return O(this[y]).size}has(a){return O(this[y]).has(a)}set(a,c){let P=this[y];return d(P),(!O(P).has(a)||O(P).get(a)!==c)&&(r(P),z(P),P.a.set(a,!0),P.e.set(a,c),P.a.set(a,!0),pe(P,a,c)),this}delete(a){if(!this.has(a))return!1;let c=this[y];return d(c),r(c),z(c),c.t.has(a)?c.a.set(a,!1):c.a.delete(a),c.e.delete(a),!0}clear(){let a=this[y];d(a),O(a).size&&(r(a),z(a),a.a=new Map,U(a.t,c=>{a.a.set(c,!1)}),a.e.clear())}forEach(a,c){let P=this[y];O(P).forEach((_,u,g)=>{a.call(c,this.get(u),u,this)})}get(a){let c=this[y];d(c);let P=O(c).get(a);if(c.u||!D(P)||P!==c.t.get(a))return P;let _=ee(c.n,P,c,a);return r(c),c.e.set(a,_),_}keys(){return O(this[y]).keys()}values(){let a=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let c=a.next();return c.done?c:{done:!1,value:this.get(c.value)}}}}entries(){let a=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let c=a.next();if(c.done)return c;let P=this.get(c.value);return{done:!1,value:[c.value,P]}}}}[(y,Symbol.iterator)](){return this.entries()}}function t(p,M){let a=new e(p,M);return[a,a[y]]}function r(p){p.e||(p.a=new Map,p.e=new Map(p.t))}class n extends Set{constructor(a,c){super();this[y]={r:3,i:c,n:c?c.n:X(),s:!1,u:!1,e:void 0,t:a,c:this,o:new Map,g:!1,S:!1,a:void 0,f:[]}}get size(){return O(this[y]).size}has(a){let c=this[y];return d(c),c.e?!!(c.e.has(a)||c.o.has(a)&&c.e.has(c.o.get(a))):c.t.has(a)}add(a){let c=this[y];return d(c),this.has(a)||(i(c),z(c),c.e.add(a),pe(c,a,a)),this}delete(a){if(!this.has(a))return!1;let c=this[y];return d(c),i(c),z(c),c.e.delete(a)||(c.o.has(a)?c.e.delete(c.o.get(a)):!1)}clear(){let a=this[y];d(a),O(a).size&&(i(a),z(a),a.e.clear())}values(){let a=this[y];return d(a),i(a),a.e.values()}entries(){let a=this[y];return d(a),i(a),a.e.entries()}keys(){return this.values()}[(y,Symbol.iterator)](){return this.values()}forEach(a,c){let P=this.values(),_=P.next();for(;!_.done;)a.call(c,_.value,_.value,this),_=P.next()}}function o(p,M){let a=new n(p,M);return[a,a[y]]}function i(p){p.e||(p.e=new Set,p.t.forEach(M=>{if(D(M)){let a=ee(p.n,M,p,M);p.o.set(M,a),p.e.add(a)}else p.e.add(M)}))}function d(p){p.g&&b(3,JSON.stringify(O(p)))}function S(p){if(p.r===3&&p.e){let M=new Set(p.e);p.e.clear(),M.forEach(a=>{p.e.add(Ve(a))})}}ie(v,{w:t,V:o,fixSetContents:S})}function Qe(){let e=new Set(["shift","unshift"]),t=new Set(["push","pop"]),r=new Set([...t,...e]),n=new Set(["reverse","sort"]),o=new Set([...r,...n,"splice"]),i=new Set(["find","findLast"]),d=new Set(["filter","slice","concat","flat",...i,"findIndex","findLastIndex","some","every","indexOf","lastIndexOf","includes","join","toString","toLocaleString"]);function S(s){return o.has(s)}function p(s){return d.has(s)}function M(s){return S(s)||p(s)}function a(s,l){s.operationMethod=l}function c(s){s.operationMethod=void 0}function P(s,l,h=!0){Z(s);let f=l();return z(s),h&&s.a.set("length",!0),f}function _(s){s.R=!0}function u(s,l){return s<0?Math.max(l+s,0):Math.min(s,l)}function g(s,l,h){return P(s,()=>{let f=s.e[l](...h);return e.has(l)&&_(s),r.has(l)?f:s.c})}function m(s,l,h){return P(s,()=>(s.e[l](...h),_(s),s.c),!1)}function x(s,l){return function(...f){let I=l;a(s,I);try{if(S(I)){if(r.has(I))return g(s,I,f);if(n.has(I))return m(s,I,f);if(I==="splice"){let E=P(s,()=>s.e.splice(...f));return _(s),E}}else return A(s,I,f)}finally{c(s)}}}function A(s,l,h){let f=O(s);if(l==="filter"){let I=h[0],E=[];for(let T=0;T<f.length;T++)I(f[T],T,f)&&E.push(s.c[T]);return E}if(i.has(l)){let I=h[0],E=l==="find",T=E?1:-1,N=E?0:f.length-1;for(let R=N;R>=0&&R<f.length;R+=T)if(I(f[R],R,f))return s.c[R];return}if(l==="slice"){let I=h[0]??0,E=h[1]??f.length,T=u(I,f.length),N=u(E,f.length),R=[];for(let De=T;De<N;De++)R.push(s.c[De]);return R}return f[l](...h)}ie(le,{createMethodInterceptor:x,isArrayOperationMethod:M,isMutatingArrayMethod:S})}var F=new me,lt=F.produce,yt=F.produceWithPatches.bind(F),dt=F.setAutoFreeze.bind(F),pt=F.setUseStrictShallowCopy.bind(F),ht=F.setUseStrictIteration.bind(F),mt=F.applyPatches.bind(F),St=F.createDraft.bind(F),Pt=F.finishDraft.bind(F),gt=e=>e,xt=e=>e;0&&(module.exports={Immer,applyPatches,castDraft,castImmutable,createDraft,current,enableArrayMethods,enableMapSet,enablePatches,finishDraft,freeze,immerable,isDraft,isDraftable,nothing,original,produce,produceWithPatches,setAutoFreeze,setUseStrictIteration,setUseStrictShallowCopy});
+//# sourceMappingURL=immer.cjs.production.js.map
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.production.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.production.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/immer.cjs.production.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../../src/immer.ts","../../src/utils/env.ts","../../src/utils/errors.ts","../../src/utils/common.ts","../../src/utils/plugins.ts","../../src/core/scope.ts","../../src/core/finalize.ts","../../src/core/proxy.ts","../../src/core/immerClass.ts","../../src/core/current.ts","../../src/plugins/patches.ts","../../src/plugins/mapset.ts","../../src/plugins/arrayMethods.ts"],"sourcesContent":["import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = /* @__PURE__ */ immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(\n\timmer\n)\n\n/**\n * Pass false to use loose iteration that only processes enumerable string properties.\n * This skips symbols and non-enumerable properties for maximum performance.\n *\n * By default, strict iteration is enabled (includes all own properties).\n */\nexport const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(\n\timmer\n)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = /* @__PURE__ */ immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport let castDraft = <T>(value: T): Draft<T> => value as any\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport let castImmutable = <T>(value: T): Immutable<T> => value as any\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableArrayMethods} from \"./plugins/arrayMethods\"\n","// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","import {isFunction} from \"../internal\"\n\nexport const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t  ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = isFunction(e) ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nconst O = Object\n\nexport const getPrototypeOf = O.getPrototypeOf\n\nexport const CONSTRUCTOR = \"constructor\"\nexport const PROTOTYPE = \"prototype\"\n\nexport const CONFIGURABLE = \"configurable\"\nexport const ENUMERABLE = \"enumerable\"\nexport const WRITABLE = \"writable\"\nexport const VALUE = \"value\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tisArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value[CONSTRUCTOR]?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()\nconst cachedCtorStrings = new WeakMap()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || !isObjectish(value)) return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null || proto === O[PROTOTYPE]) return true\n\n\tconst Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]\n\tif (Ctor === Object) return true\n\n\tif (!isFunction(Ctor)) return false\n\n\tlet ctorString = cachedCtorStrings.get(Ctor)\n\tif (ctorString === undefined) {\n\t\tctorString = Function.toString.call(Ctor)\n\t\tcachedCtorStrings.set(Ctor, ctorString)\n\t}\n\n\treturn ctorString === objectCtorString\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n *\n * @param obj The object to iterate over\n * @param iter The iterator function\n * @param strict When true (default), includes symbols and non-enumerable properties.\n *               When false, uses looseiteration over only enumerable string properties.\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tstrict?: boolean\n): void\nexport function each(obj: any, iter: any, strict: boolean = true) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\t// If strict, we do a full iteration including symbols and non-enumerable properties\n\t\t// Otherwise, we only iterate enumerable string properties for performance\n\t\tconst keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)\n\t\tkeys.forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport let has = (\n\tthing: any,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): boolean =>\n\ttype === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: O[PROTOTYPE].hasOwnProperty.call(thing, prop)\n\n/*#__PURE__*/\nexport let get = (\n\tthing: AnyMap | AnyObject,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): any =>\n\t// @ts-ignore\n\ttype === ArchType.Map ? thing.get(prop) : thing[prop]\n\n/*#__PURE__*/\nexport let set = (\n\tthing: any,\n\tpropOrOldValue: PropertyKey,\n\tvalue: any,\n\ttype = getArchtype(thing)\n) => {\n\tif (type === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (type === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\nexport let isArray = Array.isArray\n\n/*#__PURE__*/\nexport let isMap = (target: any): target is AnyMap => target instanceof Map\n\n/*#__PURE__*/\nexport let isSet = (target: any): target is AnySet => target instanceof Set\n\nexport let isObjectish = (target: any) => typeof target === \"object\"\n\nexport let isFunction = (target: any): target is Function =>\n\ttypeof target === \"function\"\n\nexport let isBoolean = (target: any): target is boolean =>\n\ttypeof target === \"boolean\"\n\nexport function isArrayIndex(value: string | number): value is number | string {\n\tconst n = +value\n\treturn Number.isInteger(n) && String(n) === value\n}\n\nexport let getProxyDraft = <T extends any>(value: T): ImmerState | null => {\n\tif (!isObjectish(value)) return null\n\treturn (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]\n}\n\n/*#__PURE__*/\nexport let latest = (state: ImmerState): any => state.copy_ || state.base_\n\nexport let getValue = <T extends object>(value: T): T => {\n\tconst proxyDraft = getProxyDraft(value)\n\treturn proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value\n}\n\nexport let getFinalValue = (state: ImmerState): any =>\n\tstate.modified_ ? state.copy_ : state.base_\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (isArray(base)) return Array[PROTOTYPE].slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = O.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc[WRITABLE] === false) {\n\t\t\t\tdesc[WRITABLE] = true\n\t\t\t\tdesc[CONFIGURABLE] = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\t[CONFIGURABLE]: true,\n\t\t\t\t\t[WRITABLE]: true, // could live with !!desc.set as well here...\n\t\t\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t\t\t[VALUE]: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn O.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = O.create(proto)\n\t\treturn O.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tO.defineProperties(obj, {\n\t\t\tset: dontMutateMethodOverride,\n\t\t\tadd: dontMutateMethodOverride,\n\t\t\tclear: dontMutateMethodOverride,\n\t\t\tdelete: dontMutateMethodOverride\n\t\t})\n\t}\n\tO.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.values (only string-like, enumerables) instead of each()\n\t\teach(\n\t\t\tobj,\n\t\t\t(_key, value) => {\n\t\t\t\tfreeze(value, true)\n\t\t\t},\n\t\t\tfalse\n\t\t)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nconst dontMutateMethodOverride = {\n\t[VALUE]: dontMutateFrozenCollections\n}\n\nexport function isFrozen(obj: any): boolean {\n\t// Fast path: primitives and null/undefined are always \"frozen\"\n\tif (obj === null || !isObjectish(obj)) return true\n\treturn O.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie,\n\tImmerScope,\n\tProxyArrayState\n} from \"../internal\"\n\nexport const PluginMapSet = \"MapSet\"\nexport const PluginPatches = \"Patches\"\nexport const PluginArrayMethods = \"ArrayMethods\"\n\nexport type PatchesPlugin = {\n\tgeneratePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\trootScope: ImmerScope\n\t): void\n\tgenerateReplacementPatches_(\n\t\tbase: any,\n\t\treplacement: any,\n\t\trootScope: ImmerScope\n\t): void\n\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\tgetPath: (state: ImmerState) => PatchPath | null\n}\n\nexport type MapSetPlugin = {\n\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]\n\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]\n\tfixSetContents: (state: ImmerState) => void\n}\n\nexport type ArrayMethodsPlugin = {\n\tcreateMethodInterceptor: (state: ProxyArrayState, method: string) => Function\n\tisArrayOperationMethod: (method: string) => boolean\n\tisMutatingArrayMethod: (method: string) => boolean\n}\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: PatchesPlugin\n\tMapSet?: MapSetPlugin\n\tArrayMethods?: ArrayMethodsPlugin\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>\n\t!!plugins[pluginKey]\n\nexport let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {\n\tdelete plugins[pluginKey]\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin,\n\tPatchesPlugin,\n\tMapSetPlugin,\n\tisPluginLoaded,\n\tPluginMapSet,\n\tPluginPatches,\n\tArrayMethodsPlugin,\n\tPluginArrayMethods\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tpatchPlugin_?: PatchesPlugin\n\tmapSetPlugin_?: MapSetPlugin\n\tarrayMethodsPlugin_?: ArrayMethodsPlugin\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n\thandledSet_: Set<any>\n\tprocessedForPatches_: Set<any>\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport let getCurrentScope = () => currentScope!\n\nlet createScope = (\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope => ({\n\tdrafts_: [],\n\tparent_,\n\timmer_,\n\t// Whenever the modified draft contains a draft from another scope, we\n\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\tcanAutoFreeze_: true,\n\tunfinalizedDrafts_: 0,\n\thandledSet_: new Set(),\n\tprocessedForPatches_: new Set(),\n\tmapSetPlugin_: isPluginLoaded(PluginMapSet)\n\t\t? getPlugin(PluginMapSet)\n\t\t: undefined,\n\tarrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods)\n\t\t? getPlugin(PluginArrayMethods)\n\t\t: undefined\n})\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tscope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport let enterScope = (immer: Immer) =>\n\t(currentScope = createScope(currentScope, immer))\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tget,\n\tPatch,\n\tlatest,\n\tprepareCopy,\n\tgetFinalValue,\n\tgetValue,\n\tProxyArrayState\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t}\n\t\tconst {patchPlugin_} = scope\n\t\tif (patchPlugin_) {\n\t\t\tpatchPlugin_.generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft)\n\t}\n\n\tmaybeFreeze(scope, result, true)\n\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\tif (!state) {\n\t\tconst finalValue = handleValue(value, rootScope.handledSet_, rootScope)\n\t\treturn finalValue\n\t}\n\n\t// Never finalize drafts owned by another scope\n\tif (!isSameScope(state, rootScope)) {\n\t\treturn value\n\t}\n\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\treturn state.base_\n\t}\n\n\tif (!state.finalized_) {\n\t\t// Execute all registered draft finalization callbacks\n\t\tconst {callbacks_} = state\n\t\tif (callbacks_) {\n\t\t\twhile (callbacks_.length > 0) {\n\t\t\t\tconst callback = callbacks_.pop()!\n\t\t\t\tcallback(rootScope)\n\t\t\t}\n\t\t}\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t}\n\n\t// By now the root copy has been fully updated throughout its tree\n\treturn state.copy_\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n\nfunction markStateFinalized(state: ImmerState) {\n\tstate.finalized_ = true\n\tstate.scope_.unfinalizedDrafts_--\n}\n\nlet isSameScope = (state: ImmerState, rootScope: ImmerScope) =>\n\tstate.scope_ === rootScope\n\n// A reusable empty array to avoid allocations\nconst EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []\n\n// Updates all references to a draft in its parent to the finalized value.\n// This handles cases where the same draft appears multiple times in the parent, or has been moved around.\nexport function updateDraftInParent(\n\tparent: ImmerState,\n\tdraftValue: any,\n\tfinalizedValue: any,\n\toriginalKey?: string | number | symbol\n): void {\n\tconst parentCopy = latest(parent)\n\tconst parentType = parent.type_\n\n\t// Fast path: Check if draft is still at original key\n\tif (originalKey !== undefined) {\n\t\tconst currentValue = get(parentCopy, originalKey, parentType)\n\t\tif (currentValue === draftValue) {\n\t\t\t// Still at original location, just update it\n\t\t\tset(parentCopy, originalKey, finalizedValue, parentType)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Slow path: Build reverse mapping of all children\n\t// to their indices in the parent, so that we can\n\t// replace all locations where this draft appears.\n\t// We only have to build this once per parent.\n\tif (!parent.draftLocations_) {\n\t\tconst draftLocations = (parent.draftLocations_ = new Map())\n\n\t\t// Use `each` which works on Arrays, Maps, and Objects\n\t\teach(parentCopy, (key, value) => {\n\t\t\tif (isDraft(value)) {\n\t\t\t\tconst keys = draftLocations.get(value) || []\n\t\t\t\tkeys.push(key)\n\t\t\t\tdraftLocations.set(value, keys)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Look up all locations where this draft appears\n\tconst locations =\n\t\tparent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT\n\n\t// Update all locations\n\tfor (const location of locations) {\n\t\tset(parentCopy, location, finalizedValue, parentType)\n\t}\n}\n\n// Register a callback to finalize a child draft when the parent draft is finalized.\n// This assumes there is a parent -> child relationship between the two drafts,\n// and we have a key to locate the child in the parent.\nexport function registerChildFinalizationCallback(\n\tparent: ImmerState,\n\tchild: ImmerState,\n\tkey: string | number | symbol\n) {\n\tparent.callbacks_.push(function childCleanup(rootScope) {\n\t\tconst state: ImmerState = child\n\n\t\t// Can only continue if this is a draft owned by this scope\n\t\tif (!state || !isSameScope(state, rootScope)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle potential set value finalization first\n\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t// Update all locations in the parent that referenced this draft\n\t\tupdateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t})\n}\n\nfunction generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {\n\tconst shouldFinalize =\n\t\tstate.modified_ &&\n\t\t!state.finalized_ &&\n\t\t(state.type_ === ArchType.Set ||\n\t\t\t(state.type_ === ArchType.Array &&\n\t\t\t\t(state as ProxyArrayState).allIndicesReassigned_) ||\n\t\t\t(state.assigned_?.size ?? 0) > 0)\n\n\tif (shouldFinalize) {\n\t\tconst {patchPlugin_} = rootScope\n\t\tif (patchPlugin_) {\n\t\t\tconst basePath = patchPlugin_!.getPath(state)\n\n\t\t\tif (basePath) {\n\t\t\t\tpatchPlugin_!.generatePatches_(state, basePath, rootScope)\n\t\t\t}\n\t\t}\n\n\t\tmarkStateFinalized(state)\n\t}\n}\n\nexport function handleCrossReference(\n\ttarget: ImmerState,\n\tkey: string | number | symbol,\n\tvalue: any\n) {\n\tconst {scope_} = target\n\t// Check if value is a draft from this scope\n\tif (isDraft(value)) {\n\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\tif (isSameScope(state, scope_)) {\n\t\t\t// Register callback to update this location when the draft finalizes\n\n\t\t\tstate.callbacks_.push(function crossReferenceCleanup() {\n\t\t\t\t// Update the target location with finalized value\n\t\t\t\tprepareCopy(target)\n\n\t\t\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t\t\tupdateDraftInParent(target, value, finalizedValue, key)\n\t\t\t})\n\t\t}\n\t} else if (isDraftable(value)) {\n\t\t// Handle non-draft objects that might contain drafts\n\t\ttarget.callbacks_.push(function nestedDraftCleanup() {\n\t\t\tconst targetCopy = latest(target)\n\n\t\t\t// For Sets, check if value is still in the set\n\t\t\tif (target.type_ === ArchType.Set) {\n\t\t\t\tif (targetCopy.has(value)) {\n\t\t\t\t\t// Process the value to replace any nested drafts\n\t\t\t\t\thandleValue(value, scope_.handledSet_, scope_)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Maps/objects\n\t\t\t\tif (get(targetCopy, key, target.type_) === value) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tscope_.drafts_.length > 1 &&\n\t\t\t\t\t\t((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??\n\t\t\t\t\t\t\tfalse) === true &&\n\t\t\t\t\t\ttarget.copy_\n\t\t\t\t\t) {\n\t\t\t\t\t\t// This might be a non-draft value that has drafts\n\t\t\t\t\t\t// inside. We do need to recurse here to handle those.\n\t\t\t\t\t\thandleValue(\n\t\t\t\t\t\t\tget(target.copy_, key, target.type_),\n\t\t\t\t\t\t\tscope_.handledSet_,\n\t\t\t\t\t\t\tscope_\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nexport function handleValue(\n\ttarget: any,\n\thandledSet: Set<any>,\n\trootScope: ImmerScope\n) {\n\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t// This benefits especially adding large data tree's without further processing.\n\t\t// See add-data.js perf test\n\t\treturn target\n\t}\n\n\t// Skip if already handled, frozen, or not draftable\n\tif (\n\t\tisDraft(target) ||\n\t\thandledSet.has(target) ||\n\t\t!isDraftable(target) ||\n\t\tisFrozen(target)\n\t) {\n\t\treturn target\n\t}\n\n\thandledSet.add(target)\n\n\t// Process ALL properties/entries\n\teach(target, (key, value) => {\n\t\tif (isDraft(value)) {\n\t\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\t\tif (isSameScope(state, rootScope)) {\n\t\t\t\t// Replace draft with finalized value\n\n\t\t\t\tconst updatedValue = getFinalValue(state)\n\n\t\t\t\tset(target, key, updatedValue, target.type_)\n\n\t\t\t\tmarkStateFinalized(state)\n\t\t\t}\n\t\t} else if (isDraftable(value)) {\n\t\t\t// Recursively handle nested values\n\t\t\thandleValue(value, handledSet, rootScope)\n\t\t}\n\t})\n\n\treturn target\n}\n","import {\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\thandleCrossReference,\n\tWRITABLE,\n\tCONFIGURABLE,\n\tENUMERABLE,\n\tVALUE,\n\tisArray,\n\tisArrayIndex\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n\toperationMethod?: string\n\tallIndicesReassigned_?: boolean\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): [Drafted<T, ProxyState>, ProxyState] {\n\tconst baseIsArray = isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: baseIsArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\t// actually instantiated in `prepareCopy()`\n\t\tassigned_: undefined,\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false,\n\t\t// `callbacks` actually gets assigned in `createProxy`\n\t\tcallbacks_: undefined as any\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (baseIsArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn [proxy as any, state]\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tlet arrayPlugin = state.scope_.arrayMethodsPlugin_\n\t\tconst isArrayWithStringProp =\n\t\t\tstate.type_ === ArchType.Array && typeof prop === \"string\"\n\t\t// Intercept array methods so that we can override\n\t\t// behavior and skip proxy creation for perf\n\t\tif (isArrayWithStringProp) {\n\t\t\tif (arrayPlugin?.isArrayOperationMethod(prop)) {\n\t\t\t\treturn arrayPlugin.createMethodInterceptor(state, prop)\n\t\t\t}\n\t\t}\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop, state.type_)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\t// During mutating array operations, defer proxy creation for array elements\n\t\t// This optimization avoids creating unnecessary proxies during sort/reverse\n\t\tif (\n\t\t\tisArrayWithStringProp &&\n\t\t\t(state as ProxyArrayState).operationMethod &&\n\t\t\tarrayPlugin?.isMutatingArrayMethod(\n\t\t\t\t(state as ProxyArrayState).operationMethod!\n\t\t\t) &&\n\t\t\tisArrayIndex(prop)\n\t\t) {\n\t\t\t// Return raw value during mutating operations, create proxy only if modified\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\t// Ensure array keys are always numbers\n\t\t\tconst childKey = state.type_ === ArchType.Array ? +(prop as string) : prop\n\t\t\tconst childDraft = createProxy(state.scope_, value, state, childKey)\n\n\t\t\treturn (state.copy_![childKey] = childDraft)\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_!.set(prop, false)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (\n\t\t\t\tis(value, current) &&\n\t\t\t\t(value !== undefined || has(state.base_, prop, state.type_))\n\t\t\t)\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_!.set(prop, true)\n\n\t\thandleCrossReference(state, prop, value)\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\tprepareCopy(state)\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_!.set(prop, false)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tstate.assigned_!.delete(prop)\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\t[WRITABLE]: true,\n\t\t\t[CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t[VALUE]: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\n// Use `for..in` instead of `each` to work around a weird\n// prod test suite issue\nfor (let key in objectTraps) {\n\tlet fn = objectTraps[key as keyof typeof objectTraps] as Function\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\tconst args = arguments\n\t\targs[0] = args[0][0]\n\t\treturn fn.apply(this, args)\n\t}\n}\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? VALUE in desc\n\t\t\t? desc[VALUE]\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t  // prototype, we should invoke it with the draft as context!\n\t\t\t  desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: ImmerState) {\n\tif (!state.copy_) {\n\t\t// Actually create the `assigned_` map now that we\n\t\t// know this is a modified draft.\n\t\tstate.assigned_ = new Map()\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent,\n\tImmerScope,\n\tregisterChildFinalizationCallback,\n\tArchType,\n\tMapSetPlugin,\n\tAnyMap,\n\tAnySet,\n\tisObjectish,\n\tisFunction,\n\tisBoolean,\n\tPluginMapSet,\n\tPluginPatches\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\"\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\tuseStrictIteration_: boolean = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t\tuseStrictIteration?: boolean\n\t}) {\n\t\tif (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)\n\t\tif (isBoolean(config?.useStrictShallowCopy))\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t\tif (isBoolean(config?.useStrictIteration))\n\t\t\tthis.setUseStrictIteration(config!.useStrictIteration)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (isFunction(base) && !isFunction(recipe)) {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (!isFunction(recipe)) die(6)\n\t\tif (patchListener !== undefined && !isFunction(patchListener)) die(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(scope, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || !isObjectish(base)) {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n\t\t\t\t\tpatches_: p,\n\t\t\t\t\tinversePatches_: ip\n\t\t\t\t} as ImmerScope) // dummy scope\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (isFunction(base)) {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(scope, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\t/**\n\t * Pass false to use faster iteration that skips non-enumerable properties\n\t * but still handles symbols for compatibility.\n\t *\n\t * By default, strict iteration is enabled (includes all own properties).\n\t */\n\tsetUseStrictIteration(value: boolean) {\n\t\tthis.useStrictIteration_ = value\n\t}\n\n\tshouldUseStrictIteration(): boolean {\n\t\treturn this.useStrictIteration_\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(PluginPatches).applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\trootScope: ImmerScope,\n\tvalue: T,\n\tparent?: ImmerState,\n\tkey?: string | number | symbol\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\t// returning a tuple here lets us skip a proxy access\n\t// to DRAFT_STATE later\n\tconst [draft, state] = isMap(value)\n\t\t? getPlugin(PluginMapSet).proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(PluginMapSet).proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent?.scope_ ?? getCurrentScope()\n\tscope.drafts_.push(draft)\n\n\t// Ensure the parent callbacks are passed down so we actually\n\t// track all callbacks added throughout the tree\n\tstate.callbacks_ = parent?.callbacks_ ?? []\n\tstate.key_ = key\n\n\tif (parent && key !== undefined) {\n\t\tregisterChildFinalizationCallback(parent, state, key)\n\t} else {\n\t\t// It's a root draft, register it with the scope\n\t\tstate.callbacks_.push(function rootDraftCleanup(rootScope) {\n\t\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\t\tconst {patchPlugin_} = rootScope\n\n\t\t\tif (state.modified_ && patchPlugin_) {\n\t\t\t\tpatchPlugin_.generatePatches_(state, [], rootScope)\n\t\t\t}\n\t\t})\n\t}\n\n\treturn draft as any\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tlet strict = true // Default to strict for compatibility\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t\tstrict = state.scope_.immer_.shouldUseStrictIteration()\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(\n\t\tcopy,\n\t\t(key, childValue) => {\n\t\t\tset(copy, key, currentImpl(childValue))\n\t\t},\n\t\tstrict\n\t)\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors,\n\tDRAFT_STATE,\n\tgetProxyDraft,\n\tImmerScope,\n\tisObjectish,\n\tisFunction,\n\tCONSTRUCTOR,\n\tPluginPatches,\n\tisArray,\n\tPROTOTYPE\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tfunction getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {\n\t\t// Step 1: Check if state has a stored key\n\t\tif (state.key_ !== undefined) {\n\t\t\t// Step 2: Validate the key is still valid in parent\n\n\t\t\tconst parentCopy = state.parent_!.copy_ ?? state.parent_!.base_\n\t\t\tconst proxyDraft = getProxyDraft(get(parentCopy, state.key_!))\n\t\t\tconst valueAtKey = get(parentCopy, state.key_!)\n\n\t\t\tif (valueAtKey === undefined) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Check if the value at the key is still related to this draft\n\t\t\t// It should be either the draft itself, the base, or the copy\n\t\t\tif (\n\t\t\t\tvalueAtKey !== state.draft_ &&\n\t\t\t\tvalueAtKey !== state.base_ &&\n\t\t\t\tvalueAtKey !== state.copy_\n\t\t\t) {\n\t\t\t\treturn null // Value was replaced with something else\n\t\t\t}\n\t\t\tif (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n\t\t\t\treturn null // Different draft\n\t\t\t}\n\n\t\t\t// Step 3: Handle Set case specially\n\t\t\tconst isSet = state.parent_!.type_ === ArchType.Set\n\t\t\tlet key: string | number\n\n\t\t\tif (isSet) {\n\t\t\t\t// For Sets, find the index in the drafts_ map\n\t\t\t\tconst setParent = state.parent_ as SetState\n\t\t\t\tkey = Array.from(setParent.drafts_.keys()).indexOf(state.key_)\n\t\t\t} else {\n\t\t\t\tkey = state.key_ as string | number\n\t\t\t}\n\n\t\t\t// Step 4: Validate key still exists in parent\n\t\t\tif (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {\n\t\t\t\treturn null // Key deleted\n\t\t\t}\n\n\t\t\t// Step 5: Add key to path\n\t\t\tpath.push(key)\n\t\t}\n\n\t\t// Step 6: Recurse to parent if exists\n\t\tif (state.parent_) {\n\t\t\treturn getPath(state.parent_, path)\n\t\t}\n\n\t\t// Step 7: At root - reverse path and validate\n\t\tpath.reverse()\n\n\t\ttry {\n\t\t\t// Validate path can be resolved from ROOT\n\t\t\tresolvePath(state.copy_, path)\n\t\t} catch (e) {\n\t\t\treturn null // Path invalid\n\t\t}\n\n\t\treturn path\n\t}\n\n\t// NEW: Add resolvePath helper function\n\tfunction resolvePath(base: any, path: PatchPath): any {\n\t\tlet current = base\n\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\tconst key = path[i]\n\t\t\tcurrent = get(current, key)\n\t\t\tif (!isObjectish(current) || current === null) {\n\t\t\t\tthrow new Error(`Cannot resolve path at '${path.join(\"/\")}'`)\n\t\t\t}\n\t\t}\n\t\treturn current\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tscope: ImmerScope\n\t): void {\n\t\tif (state.scope_.processedForPatches_.has(state)) {\n\t\t\treturn\n\t\t}\n\n\t\tstate.scope_.processedForPatches_.add(state)\n\n\t\tconst {patches_, inversePatches_} = scope\n\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\tconst allReassigned = state.allIndicesReassigned_ === true\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tconst copiedItem = copy_[i]\n\t\t\tconst baseItem = base_[i]\n\n\t\t\tconst isAssigned = allReassigned || assigned_?.get(i.toString())\n\t\t\tif (isAssigned && copiedItem !== baseItem) {\n\t\t\t\tconst childState = copiedItem?.[DRAFT_STATE]\n\t\t\t\tif (childState && childState.modified_) {\n\t\t\t\t\t// Skip - let the child generate its own patches\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copiedItem)\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(baseItem)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_, type_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key, type_)\n\t\t\tconst value = get(copy_!, key, type_)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(\n\t\t\t\top === REMOVE\n\t\t\t\t\t? {op, path}\n\t\t\t\t\t: {op, path, value: clonePatchValueIfNeeded(value)}\n\t\t\t)\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tscope: ImmerScope\n\t): void {\n\t\tconst {patches_, inversePatches_} = scope\n\t\tpatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === CONSTRUCTOR)\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (!isObjectish(base)) die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(PluginPatches, {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_,\n\t\tgetPath\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach,\n\tgetValue,\n\tPluginMapSet,\n\thandleCrossReference\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\thandleCrossReference(state, key, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_, value, state, key)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, MapState] {\n\t\t// @ts-ignore\n\t\tconst map = new DraftMap(target, parent)\n\t\treturn [map as any, map[DRAFT_STATE]]\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t\thandleCrossReference(state, value, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, SetState] {\n\t\t// @ts-ignore\n\t\tconst set = new DraftSet(target, parent)\n\t\treturn [set as any, set[DRAFT_STATE]]\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_, value, state, value)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tfunction fixSetContents(target: ImmerState) {\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\tif (target.type_ === ArchType.Set && target.copy_) {\n\t\t\tconst copy = new Set(target.copy_)\n\t\t\ttarget.copy_.clear()\n\t\t\tcopy.forEach(value => {\n\t\t\t\ttarget.copy_!.add(getValue(value))\n\t\t\t})\n\t\t}\n\t}\n\n\tloadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})\n}\n","import {\n\tPluginArrayMethods,\n\tlatest,\n\tloadPlugin,\n\tmarkChanged,\n\tprepareCopy,\n\tProxyArrayState\n} from \"../internal\"\n\n/**\n * Methods that directly modify the array in place.\n * These operate on the copy without creating per-element proxies:\n * - `push`, `pop`: Add/remove from end\n * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)\n * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)\n * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)\n */\ntype MutatingArrayMethod =\n\t| \"push\"\n\t| \"pop\"\n\t| \"shift\"\n\t| \"unshift\"\n\t| \"splice\"\n\t| \"reverse\"\n\t| \"sort\"\n\n/**\n * Methods that read from the array without modifying it.\n * These fall into distinct categories based on return semantics:\n *\n * **Subset operations** (return drafts - mutations propagate):\n * - `filter`, `slice`: Return array of draft proxies\n * - `find`, `findLast`: Return single draft proxy or undefined\n *\n * **Transform operations** (return base values - mutations don't track):\n * - `concat`, `flat`: Create new structures, not subsets of original\n *\n * **Primitive-returning** (no draft needed):\n * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers\n * - `some`, `every`, `includes`: Return booleans\n * - `join`, `toString`, `toLocaleString`: Return strings\n */\ntype NonMutatingArrayMethod =\n\t| \"filter\"\n\t| \"slice\"\n\t| \"concat\"\n\t| \"flat\"\n\t| \"find\"\n\t| \"findIndex\"\n\t| \"findLast\"\n\t| \"findLastIndex\"\n\t| \"some\"\n\t| \"every\"\n\t| \"indexOf\"\n\t| \"lastIndexOf\"\n\t| \"includes\"\n\t| \"join\"\n\t| \"toString\"\n\t| \"toLocaleString\"\n\n/** Union of all array operation methods handled by the plugin. */\nexport type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod\n\n/**\n * Enables optimized array method handling for Immer drafts.\n *\n * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,\n * significantly improving performance for array-heavy operations.\n *\n * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):\n * Operate directly on the copy without creating per-element proxies.\n *\n * **Non-mutating methods** fall into categories:\n * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track\n * - **Transform operations** (concat, flat): Return base values - mutations don't track\n * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives\n *\n * **Important**: Callbacks for overridden methods receive base values, not drafts.\n * This is the core performance optimization.\n *\n * @example\n * ```ts\n * import { enableArrayMethods, produce } from \"immer\"\n *\n * enableArrayMethods()\n *\n * const next = produce(state, draft => {\n *   // Optimized - no proxy creation per element\n *   draft.items.sort((a, b) => a.value - b.value)\n *\n *   // filter returns drafts - mutations propagate\n *   const filtered = draft.items.filter(x => x.value > 5)\n *   filtered[0].value = 999 // Affects draft.items[originalIndex]\n * })\n * ```\n *\n * @see https://immerjs.github.io/immer/array-methods\n */\nexport function enableArrayMethods() {\n\tconst SHIFTING_METHODS = new Set<MutatingArrayMethod>([\"shift\", \"unshift\"])\n\n\tconst QUEUE_METHODS = new Set<MutatingArrayMethod>([\"push\", \"pop\"])\n\n\tconst RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...QUEUE_METHODS,\n\t\t...SHIFTING_METHODS\n\t])\n\n\tconst REORDERING_METHODS = new Set<MutatingArrayMethod>([\"reverse\", \"sort\"])\n\n\t// Optimized method detection using array-based lookup\n\tconst MUTATING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...RESULT_RETURNING_METHODS,\n\t\t...REORDERING_METHODS,\n\t\t\"splice\"\n\t])\n\n\tconst FIND_METHODS = new Set<NonMutatingArrayMethod>([\"find\", \"findLast\"])\n\n\tconst NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([\n\t\t\"filter\",\n\t\t\"slice\",\n\t\t\"concat\",\n\t\t\"flat\",\n\t\t...FIND_METHODS,\n\t\t\"findIndex\",\n\t\t\"findLastIndex\",\n\t\t\"some\",\n\t\t\"every\",\n\t\t\"indexOf\",\n\t\t\"lastIndexOf\",\n\t\t\"includes\",\n\t\t\"join\",\n\t\t\"toString\",\n\t\t\"toLocaleString\"\n\t])\n\n\t// Type guard for method detection\n\tfunction isMutatingArrayMethod(\n\t\tmethod: string\n\t): method is MutatingArrayMethod {\n\t\treturn MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isNonMutatingArrayMethod(\n\t\tmethod: string\n\t): method is NonMutatingArrayMethod {\n\t\treturn NON_MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isArrayOperationMethod(\n\t\tmethod: string\n\t): method is ArrayOperationMethod {\n\t\treturn isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)\n\t}\n\n\tfunction enterOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: ArrayOperationMethod\n\t) {\n\t\tstate.operationMethod = method\n\t}\n\n\tfunction exitOperation(state: ProxyArrayState) {\n\t\tstate.operationMethod = undefined\n\t}\n\n\t// Shared utility functions for array method handlers\n\tfunction executeArrayMethod<T>(\n\t\tstate: ProxyArrayState,\n\t\toperation: () => T,\n\t\tmarkLength = true\n\t): T {\n\t\tprepareCopy(state)\n\t\tconst result = operation()\n\t\tmarkChanged(state)\n\t\tif (markLength) state.assigned_!.set(\"length\", true)\n\t\treturn result\n\t}\n\n\tfunction markAllIndicesReassigned(state: ProxyArrayState) {\n\t\tstate.allIndicesReassigned_ = true\n\t}\n\n\tfunction normalizeSliceIndex(index: number, length: number): number {\n\t\tif (index < 0) {\n\t\t\treturn Math.max(length + index, 0)\n\t\t}\n\t\treturn Math.min(index, length)\n\t}\n\n\t/**\n\t * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).\n\t *\n\t * Operates directly on `state.copy_` without creating per-element proxies.\n\t * For shifting methods (shift, unshift), marks all indices as reassigned since\n\t * indices shift.\n\t *\n\t * @returns For push/pop/shift/unshift: the native method result. For others: the draft.\n\t */\n\tfunction handleSimpleOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(state, () => {\n\t\t\tconst result = (state.copy_! as any)[method](...args)\n\n\t\t\t// Handle index reassignment for shifting methods\n\t\t\tif (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t}\n\n\t\t\t// Return appropriate value based on method\n\t\t\treturn RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)\n\t\t\t\t? result\n\t\t\t\t: state.draft_\n\t\t})\n\t}\n\n\t/**\n\t * Handles reordering operations (reverse, sort) that change element order.\n\t *\n\t * Operates directly on `state.copy_` and marks all indices as reassigned\n\t * since element positions change. Does not mark length as changed since\n\t * these operations preserve array length.\n\t *\n\t * @returns The draft proxy for method chaining.\n\t */\n\tfunction handleReorderingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(\n\t\t\tstate,\n\t\t\t() => {\n\t\t\t\t;(state.copy_! as any)[method](...args)\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\treturn state.draft_\n\t\t\t},\n\t\t\tfalse\n\t\t) // Don't mark length as changed\n\t}\n\n\t/**\n\t * Creates an interceptor function for a specific array method.\n\t *\n\t * The interceptor wraps array method calls to:\n\t * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap\n\t *    to detect we're inside an optimized method and skip proxy creation)\n\t * 2. Route to appropriate handler based on method type\n\t * 3. Clean up the operation flag in `finally` block\n\t *\n\t * The `operationMethod` flag is the key mechanism that enables the proxy's `get`\n\t * trap to return base values instead of creating nested proxies during iteration.\n\t *\n\t * @param state - The proxy array state\n\t * @param originalMethod - Name of the array method being intercepted\n\t * @returns Interceptor function that handles the method call\n\t */\n\tfunction createMethodInterceptor(\n\t\tstate: ProxyArrayState,\n\t\toriginalMethod: string\n\t) {\n\t\treturn function interceptedMethod(...args: any[]) {\n\t\t\t// Enter operation mode - this flag tells the proxy's get trap to return\n\t\t\t// base values instead of creating nested proxies during iteration\n\t\t\tconst method = originalMethod as ArrayOperationMethod\n\t\t\tenterOperation(state, method)\n\n\t\t\ttry {\n\t\t\t\t// Check if this is a mutating method\n\t\t\t\tif (isMutatingArrayMethod(method)) {\n\t\t\t\t\t// Direct method dispatch - no configuration lookup needed\n\t\t\t\t\tif (RESULT_RETURNING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleSimpleOperation(state, method, args)\n\t\t\t\t\t}\n\t\t\t\t\tif (REORDERING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleReorderingOperation(state, method, args)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === \"splice\") {\n\t\t\t\t\t\tconst res = executeArrayMethod(state, () =>\n\t\t\t\t\t\t\tstate.copy_!.splice(...(args as [number, number, ...any[]]))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\t\t\treturn res\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle non-mutating methods\n\t\t\t\t\treturn handleNonMutatingOperation(state, method, args)\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// Always exit operation mode - must be in finally to handle exceptions\n\t\t\t\texitOperation(state)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Handles non-mutating array methods with different return semantics.\n\t *\n\t * **Subset operations** return draft proxies for mutation tracking:\n\t * - `filter`, `slice`: Return `state.draft_[i]` for each selected element\n\t * - `find`, `findLast`: Return `state.draft_[i]` for the found element\n\t *\n\t * This allows mutations on returned elements to propagate back to the draft:\n\t * ```ts\n\t * const filtered = draft.items.filter(x => x.value > 5)\n\t * filtered[0].value = 999 // Mutates draft.items[originalIndex]\n\t * ```\n\t *\n\t * **Transform operations** return base values (no draft tracking):\n\t * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.\n\t *   Since the result structure differs from the original, tracking mutations\n\t *   back to specific draft indices would be impractical/impossible.\n\t *\n\t * **Primitive operations** return the native result directly:\n\t * - `indexOf`, `includes`, `some`, `every`, `join`, etc.\n\t *\n\t * @param state - The proxy array state\n\t * @param method - The non-mutating method name\n\t * @param args - Arguments passed to the method\n\t * @returns Drafts for subset operations, base values for transforms, primitives otherwise\n\t */\n\tfunction handleNonMutatingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: NonMutatingArrayMethod,\n\t\targs: any[]\n\t) {\n\t\tconst source = latest(state)\n\n\t\t// Methods that return arrays with selected items - need to return drafts\n\t\tif (method === \"filter\") {\n\t\t\tconst predicate = args[0]\n\t\t\tconst result: any[] = []\n\n\t\t\t// First pass: call predicate on base values to determine which items pass\n\t\t\tfor (let i = 0; i < source.length; i++) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\t// Only create draft for items that passed the predicate\n\t\t\t\t\tresult.push(state.draft_[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\tif (FIND_METHODS.has(method)) {\n\t\t\tconst predicate = args[0]\n\t\t\tconst isForward = method === \"find\"\n\t\t\tconst step = isForward ? 1 : -1\n\t\t\tconst start = isForward ? 0 : source.length - 1\n\n\t\t\tfor (let i = start; i >= 0 && i < source.length; i += step) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\treturn state.draft_[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (method === \"slice\") {\n\t\t\tconst rawStart = args[0] ?? 0\n\t\t\tconst rawEnd = args[1] ?? source.length\n\n\t\t\t// Normalize negative indices\n\t\t\tconst start = normalizeSliceIndex(rawStart, source.length)\n\t\t\tconst end = normalizeSliceIndex(rawEnd, source.length)\n\n\t\t\tconst result: any[] = []\n\n\t\t\t// Return drafts for items in the slice range\n\t\t\tfor (let i = start; i < end; i++) {\n\t\t\t\tresult.push(state.draft_[i])\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\t// For other methods, call on base array directly:\n\t\t// - indexOf, includes, join, toString: Return primitives, no draft needed\n\t\t// - concat, flat: Return NEW arrays (not subsets). Elements are base values.\n\t\t//   This is intentional - concat/flat create new data structures rather than\n\t\t//   selecting subsets of the original, making draft tracking impractical.\n\t\treturn source[method as keyof typeof Array.prototype](...args)\n\t}\n\n\tloadPlugin(PluginArrayMethods, {\n\t\tcreateMethodInterceptor,\n\t\tisArrayOperationMethod,\n\t\tisMutatingArrayMethod\n\t})\n}\n"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,WAAAE,GAAA,iBAAAC,GAAA,cAAAC,GAAA,kBAAAC,GAAA,gBAAAC,GAAA,YAAAC,GAAA,uBAAAC,GAAA,iBAAAC,GAAA,kBAAAC,GAAA,gBAAAC,GAAA,WAAAC,EAAA,cAAAC,EAAA,YAAAC,EAAA,gBAAAC,EAAA,YAAAC,EAAA,aAAAC,GAAA,YAAAC,GAAA,uBAAAC,GAAA,kBAAAC,GAAA,0BAAAC,GAAA,4BAAAC,KAAA,eAAAC,GAAAvB,ICKO,IAAMwB,EAAyB,OAAO,IAAI,eAAe,EAUnDC,EAA2B,OAAO,IAAI,iBAAiB,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AOaO,GAA+BP,EAAM,aAAa,KAAKA,CAAK,EAM5DQ,GAA8BR,EAAM,YAAY,KAAKA,CAAK,EAU1DS,GAA8BT,EAAM,YAAY,KAAKA,CAAK,EAQ5DU,GAAgBC,GAAuBA,EAOvCC,GAAoBD,GAA2BA","names":["immer_exports","__export","Immer","applyPatches","castDraft","castImmutable","createDraft","current","enableArrayMethods","enableMapSet","enablePatches","finishDraft","freeze","DRAFTABLE","isDraft","isDraftable","NOTHING","original","produce","produceWithPatches","setAutoFreeze","setUseStrictIteration","setUseStrictShallowCopy","__toCommonJS","NOTHING","DRAFTABLE","DRAFT_STATE","die","error","args","O","getPrototypeOf","CONSTRUCTOR","PROTOTYPE","CONFIGURABLE","ENUMERABLE","WRITABLE","VALUE","isDraft","value","DRAFT_STATE","isDraftable","isPlainObject","isArray","DRAFTABLE","isMap","isSet","objectCtorString","cachedCtorStrings","isObjectish","proto","Ctor","isFunction","ctorString","original","die","base_","each","obj","iter","strict","getArchtype","key","entry","index","thing","state","type_","has","prop","type","get","set","propOrOldValue","is","x","y","target","isBoolean","isArrayIndex","n","getProxyDraft","latest","copy_","getValue","proxyDraft","getFinalValue","modified_","shallowCopy","base","isPlain","descriptors","keys","desc","freeze","deep","isFrozen","dontMutateMethodOverride","_key","dontMutateFrozenCollections","PluginMapSet","PluginPatches","PluginArrayMethods","plugins","getPlugin","pluginKey","plugin","die","isPluginLoaded","loadPlugin","pluginKey","implementation","plugins","currentScope","getCurrentScope","createScope","parent_","immer_","drafts_","canAutoFreeze_","unfinalizedDrafts_","handledSet_","processedForPatches_","mapSetPlugin_","isPluginLoaded","PluginMapSet","getPlugin","arrayMethodsPlugin_","PluginArrayMethods","usePatchesInScope","scope","patchListener","patchPlugin_","PluginPatches","patches_","inversePatches_","patchListener_","revokeScope","leaveScope","revokeDraft","enterScope","immer","draft","state","DRAFT_STATE","type_","revoke_","revoked_","processResult","result","scope","unfinalizedDrafts_","drafts_","baseDraft","DRAFT_STATE","modified_","revokeScope","die","isDraftable","finalize","patchPlugin_","generateReplacementPatches_","base_","maybeFreeze","patches_","patchListener_","inversePatches_","NOTHING","rootScope","value","isFrozen","state","handleValue","handledSet_","isSameScope","finalized_","callbacks_","generatePatchesAndFinalize","copy_","deep","parent_","immer_","autoFreeze_","canAutoFreeze_","freeze","markStateFinalized","scope_","EMPTY_LOCATIONS_RESULT","updateDraftInParent","parent","draftValue","finalizedValue","originalKey","parentCopy","latest","parentType","type_","get","set","draftLocations_","draftLocations","each","key","isDraft","keys","locations","location","registerChildFinalizationCallback","child","mapSetPlugin_","getFinalValue","draft_","allIndicesReassigned_","assigned_","basePath","generatePatches_","handleCrossReference","target","prepareCopy","targetCopy","handledSet","updatedValue","createProxyProxy","base","parent","baseIsArray","isArray","state","type_","scope_","getCurrentScope","modified_","finalized_","assigned_","parent_","base_","draft_","copy_","revoke_","isManual_","callbacks_","target","traps","objectTraps","arrayTraps","revoke","proxy","prop","DRAFT_STATE","arrayPlugin","arrayMethodsPlugin_","isArrayWithStringProp","source","latest","has","readPropFromProto","value","isDraftable","isArrayIndex","peek","prepareCopy","childKey","childDraft","createProxy","desc","getDescriptorFromProto","current","currentState","is","markChanged","handleCrossReference","owner","WRITABLE","CONFIGURABLE","ENUMERABLE","VALUE","die","getPrototypeOf","key","fn","args","draft","proto","shallowCopy","immer_","useStrictShallowCopy_","Immer","config","autoFreeze_","useStrictShallowCopy_","useStrictIteration_","base","recipe","patchListener","isFunction","defaultBase","self","args","draft","die","result","isDraftable","scope","enterScope","proxy","createProxy","hasError","revokeScope","leaveScope","usePatchesInScope","processResult","isObjectish","NOTHING","freeze","p","ip","getPlugin","PluginPatches","generateReplacementPatches_","patches_","inversePatches_","state","patches","inversePatches","isBoolean","isDraft","current","DRAFT_STATE","isManual_","scope_","value","i","patch","applyPatchesImpl","applyPatches_","rootScope","parent","key","isMap","PluginMapSet","proxyMap_","isSet","proxySet_","createProxyProxy","getCurrentScope","drafts_","callbacks_","key_","registerChildFinalizationCallback","mapSetPlugin_","patchPlugin_","modified_","generatePatches_","current","value","isDraft","die","currentImpl","isDraftable","isFrozen","state","DRAFT_STATE","copy","strict","modified_","base_","finalized_","shallowCopy","scope_","immer_","useStrictShallowCopy_","each","key","childValue","set","enablePatches","getPath","state","path","key_","parentCopy","parent_","copy_","base_","proxyDraft","getProxyDraft","get","valueAtKey","draft_","isSet","type_","key","setParent","drafts_","has","resolvePath","base","current","i","isObjectish","REPLACE","ADD","REMOVE","generatePatches_","basePath","scope","scope_","processedForPatches_","patches_","inversePatches_","generatePatchesFromAssigned","generateArrayPatches","generateSetPatches","patches","inversePatches","assigned_","allReassigned","allIndicesReassigned_","copiedItem","baseItem","childState","DRAFT_STATE","modified_","clonePatchValueIfNeeded","each","assignedValue","origValue","value","op","generateReplacementPatches_","baseValue","replacement","NOTHING","applyPatches_","draft","patch","parentType","getArchtype","p","CONSTRUCTOR","die","isFunction","PROTOTYPE","type","deepClonePatchValue","obj","isDraftable","isArray","isMap","k","v","cloned","getPrototypeOf","DRAFTABLE","isDraft","loadPlugin","PluginPatches","enableMapSet","DraftMap","target","parent","DRAFT_STATE","type_","parent_","scope_","getCurrentScope","modified_","finalized_","copy_","assigned_","base_","draft_","isManual_","revoked_","callbacks_","latest","key","value","state","assertUnrevoked","prepareMapCopy","markChanged","handleCrossReference","each","cb","thisArg","_value","_map","isDraftable","draft","createProxy","iterator","r","proxyMap_","map","DraftSet","drafts_","prepareSetCopy","result","proxySet_","set","die","fixSetContents","copy","getValue","loadPlugin","PluginMapSet","enableArrayMethods","SHIFTING_METHODS","QUEUE_METHODS","RESULT_RETURNING_METHODS","REORDERING_METHODS","MUTATING_METHODS","FIND_METHODS","NON_MUTATING_METHODS","isMutatingArrayMethod","method","isNonMutatingArrayMethod","isArrayOperationMethod","enterOperation","state","exitOperation","executeArrayMethod","operation","markLength","prepareCopy","result","markChanged","assigned_","markAllIndicesReassigned","allIndicesReassigned_","normalizeSliceIndex","index","length","handleSimpleOperation","args","copy_","draft_","handleReorderingOperation","createMethodInterceptor","originalMethod","res","handleNonMutatingOperation","source","latest","predicate","i","isForward","step","start","rawStart","rawEnd","end","loadPlugin","PluginArrayMethods","immer","Immer","produce","produceWithPatches","setAutoFreeze","setUseStrictShallowCopy","setUseStrictIteration","applyPatches","createDraft","finishDraft","castDraft","value","castImmutable"]}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/index.js
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/index.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+
+'use strict'
+
+if (process.env.NODE_ENV === 'production') {
+  module.exports = require('./immer.cjs.production.js')
+} else {
+  module.exports = require('./immer.cjs.development.js')
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/index.js.flow
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/index.js.flow	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/cjs/index.js.flow	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,112 @@
+// @flow
+
+export interface Patch {
+	op: "replace" | "remove" | "add";
+	path: (string | number)[];
+	value?: any;
+}
+
+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void
+
+type Base = {...} | Array<any>
+interface IProduce {
+	/**
+	 * Immer takes a state, and runs a function against it.
+	 * That function can freely mutate the state, as it will create copies-on-write.
+	 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.
+	 *
+	 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe
+	 * any time it is called with the current state.
+	 *
+	 * @param currentState - the state to start with
+	 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified
+	 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined
+	 * @returns The next state: a new state, or the current state if nothing was modified
+	 */
+	<S: Base>(
+		currentState: S,
+		recipe: (draftState: S) => S | void,
+		patchListener?: PatchListener
+	): S;
+	// curried invocations with initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,
+		initialState: S
+	): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => S;
+	// curried invocations without initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void
+	): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S;
+}
+
+interface IProduceWithPatches {
+        /**
+         * Like `produce`, but instead of just returning the new state,
+         * a tuple is returned with [nextState, patches, inversePatches]
+         *
+         * Like produce, this function supports currying
+         */
+	<S: Base>(
+		currentState: S,
+		recipe: (draftState: S) => S | void
+	): [S, Patch[], Patch[]];
+	// curried invocations with initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,
+		initialState: S
+	): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => [S, Patch[], Patch[]];
+	// curried invocations without initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void
+	): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => [S, Patch[], Patch[]];
+}
+
+declare export var produce: IProduce
+
+declare export var produceWithPatches: IProduceWithPatches
+
+declare export var nothing: typeof undefined
+
+declare export var immerable: Symbol
+
+/**
+ * Automatically freezes any state trees generated by immer.
+ * This protects against accidental modifications of the state tree outside of an immer function.
+ * This comes with a performance impact, so it is recommended to disable this option in production.
+ * By default it is turned on during local development, and turned off in production.
+ */
+declare export function setAutoFreeze(autoFreeze: boolean): void
+
+/**
+ * Pass false to disable strict shallow copy.
+ *
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+ */
+declare export function setUseStrictShallowCopy(useStrictShallowCopy: boolean): void
+
+declare export function applyPatches<S>(state: S, patches: Patch[]): S
+
+declare export function original<S>(value: S): S
+
+declare export function current<S>(value: S): S
+
+declare export function isDraft(value: any): boolean
+
+/**
+ * Creates a mutable draft from an (immutable) object / array.
+ * The draft can be modified until `finishDraft` is called
+ */
+declare export function createDraft<T>(base: T): T
+
+/**
+ * Given a draft that was created using `createDraft`,
+ * finalizes the draft into a new immutable object.
+ * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.
+ */
+declare export function finishDraft<T>(base: T, listener?: PatchListener): T
+
+declare export function enableMapSet(): void
+declare export function enablePatches(): void
+declare export function enableArrayMethods(): void
+
+declare export function freeze<T>(obj: T, freeze?: boolean): T
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,317 @@
+/**
+ * The sentinel value returned by producers to replace the draft with undefined.
+ */
+declare const NOTHING: unique symbol;
+/**
+ * To let Immer treat your class instances as plain immutable objects
+ * (albeit with a custom prototype), you must define either an instance property
+ * or a static property on each of your custom classes.
+ *
+ * Otherwise, your class instance will never be drafted, which means it won't be
+ * safe to mutate in a produce callback.
+ */
+declare const DRAFTABLE: unique symbol;
+
+type AnyFunc = (...args: any[]) => any;
+type PrimitiveType = number | string | boolean;
+/** Object types that should never be mapped */
+type AtomicObject = Function | Promise<any> | Date | RegExp;
+/**
+ * If the lib "ES2015.Collection" is not included in tsconfig.json,
+ * types like ReadonlyArray, WeakMap etc. fall back to `any` (specified nowhere)
+ * or `{}` (from the node types), in both cases entering an infinite recursion in
+ * pattern matching type mappings
+ * This type can be used to cast these types to `void` in these cases.
+ */
+type IfAvailable<T, Fallback = void> = true | false extends (T extends never ? true : false) ? Fallback : keyof T extends never ? Fallback : T;
+/**
+ * These should also never be mapped but must be tested after regular Map and
+ * Set
+ */
+type WeakReferences = IfAvailable<WeakMap<any, any>> | IfAvailable<WeakSet<any>>;
+type WritableDraft<T> = T extends any[] ? number extends T["length"] ? Draft<T[number]>[] : WritableNonArrayDraft<T> : WritableNonArrayDraft<T>;
+type WritableNonArrayDraft<T> = {
+    -readonly [K in keyof T]: T[K] extends infer V ? V extends object ? Draft<V> : V : never;
+};
+/** Convert a readonly type into a mutable type, if possible */
+type Draft<T> = T extends PrimitiveType ? T : T extends AtomicObject ? T : T extends ReadonlyMap<infer K, infer V> ? Map<Draft<K>, Draft<V>> : T extends ReadonlySet<infer V> ? Set<Draft<V>> : T extends WeakReferences ? T : T extends object ? WritableDraft<T> : T;
+/** Convert a mutable type into a readonly type */
+type Immutable<T> = T extends PrimitiveType ? T : T extends AtomicObject ? T : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Immutable<K>, Immutable<V>> : T extends ReadonlySet<infer V> ? ReadonlySet<Immutable<V>> : T extends WeakReferences ? T : T extends object ? {
+    readonly [K in keyof T]: Immutable<T[K]>;
+} : T;
+interface Patch {
+    op: "replace" | "remove" | "add";
+    path: (string | number)[];
+    value?: any;
+}
+type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void;
+/**
+ * Utility types
+ */
+type PatchesTuple<T> = readonly [T, Patch[], Patch[]];
+type ValidRecipeReturnType<State> = State | void | undefined | (State extends undefined ? typeof NOTHING : never);
+type ReturnTypeWithPatchesIfNeeded<State, UsePatches extends boolean> = UsePatches extends true ? PatchesTuple<State> : State;
+/**
+ * Core Producer inference
+ */
+type InferRecipeFromCurried<Curried> = Curried extends (base: infer State, ...rest: infer Args) => any ? ReturnType<Curried> extends State ? (draft: Draft<State>, ...rest: Args) => ValidRecipeReturnType<Draft<State>> : never : never;
+type InferInitialStateFromCurried<Curried> = Curried extends (base: infer State, ...rest: any[]) => any ? State : never;
+type InferCurriedFromRecipe<Recipe, UsePatches extends boolean> = Recipe extends (draft: infer DraftState, ...args: infer RestArgs) => any ? ReturnType<Recipe> extends ValidRecipeReturnType<DraftState> ? (base: Immutable<DraftState>, ...args: RestArgs) => ReturnTypeWithPatchesIfNeeded<DraftState, UsePatches> : never : never;
+type InferCurriedFromInitialStateAndRecipe<State, Recipe, UsePatches extends boolean> = Recipe extends (draft: Draft<State>, ...rest: infer RestArgs) => ValidRecipeReturnType<State> ? (base?: State | undefined, ...args: RestArgs) => ReturnTypeWithPatchesIfNeeded<State, UsePatches> : never;
+/**
+ * The `produce` function takes a value and a "recipe function" (whose
+ * return value often depends on the base state). The recipe function is
+ * free to mutate its first argument however it wants. All mutations are
+ * only ever applied to a __copy__ of the base state.
+ *
+ * Pass only a function to create a "curried producer" which relieves you
+ * from passing the recipe function every time.
+ *
+ * Only plain objects and arrays are made mutable. All other objects are
+ * considered uncopyable.
+ *
+ * Note: This function is __bound__ to its `Immer` instance.
+ *
+ * @param {any} base - the initial state
+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
+ * @returns {any} a new state, or the initial state if nothing was modified
+ */
+interface IProduce {
+    /** Curried producer that infers the recipe from the curried output function (e.g. when passing to setState) */
+    <Curried>(recipe: InferRecipeFromCurried<Curried>, initialState?: InferInitialStateFromCurried<Curried>): Curried;
+    /** Curried producer that infers curried from the recipe  */
+    <Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<Recipe, false>;
+    /** Curried producer that infers curried from the State generic, which is explicitly passed in.  */
+    <State>(recipe: (state: Draft<State>, initialState: State) => ValidRecipeReturnType<State>): (state?: State) => State;
+    <State, Args extends any[]>(recipe: (state: Draft<State>, ...args: Args) => ValidRecipeReturnType<State>, initialState: State): (state?: State, ...args: Args) => State;
+    <State>(recipe: (state: Draft<State>) => ValidRecipeReturnType<State>): (state: State) => State;
+    <State, Args extends any[]>(recipe: (state: Draft<State>, ...args: Args) => ValidRecipeReturnType<State>): (state: State, ...args: Args) => State;
+    /** Curried producer with initial state, infers recipe from initial state */
+    <State, Recipe extends Function>(recipe: Recipe, initialState: State): InferCurriedFromInitialStateAndRecipe<State, Recipe, false>;
+    /** Normal producer */
+    <Base, D = Draft<Base>>(// By using a default inferred D, rather than Draft<Base> in the recipe, we can override it.
+    base: Base, recipe: (draft: D) => ValidRecipeReturnType<D>, listener?: PatchListener): Base;
+}
+/**
+ * Like `produce`, but instead of just returning the new state,
+ * a tuple is returned with [nextState, patches, inversePatches]
+ *
+ * Like produce, this function supports currying
+ */
+interface IProduceWithPatches {
+    <Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<Recipe, true>;
+    <State, Recipe extends Function>(recipe: Recipe, initialState: State): InferCurriedFromInitialStateAndRecipe<State, Recipe, true>;
+    <Base, D = Draft<Base>>(base: Base, recipe: (draft: D) => ValidRecipeReturnType<D>, listener?: PatchListener): PatchesTuple<Base>;
+}
+/**
+ * The type for `recipe function`
+ */
+type Producer<T> = (draft: Draft<T>) => ValidRecipeReturnType<Draft<T>>;
+
+type Objectish = AnyObject | AnyArray | AnyMap | AnySet;
+type AnyObject = {
+    [key: string]: any;
+};
+type AnyArray = Array<any>;
+type AnySet = Set<any>;
+type AnyMap = Map<any, any>;
+
+/** Returns true if the given value is an Immer draft */
+declare let isDraft: (value: any) => boolean;
+/** Returns true if the given value can be drafted by Immer */
+declare function isDraftable(value: any): boolean;
+/** Get the underlying object that is represented by the given draft */
+declare function original<T>(value: T): T | undefined;
+/**
+ * Freezes draftable objects. Returns the original object.
+ * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.
+ *
+ * @param obj
+ * @param deep
+ */
+declare function freeze<T>(obj: T, deep?: boolean): T;
+
+interface ProducersFns {
+    produce: IProduce;
+    produceWithPatches: IProduceWithPatches;
+}
+type StrictMode = boolean | "class_only";
+declare class Immer implements ProducersFns {
+    autoFreeze_: boolean;
+    useStrictShallowCopy_: StrictMode;
+    useStrictIteration_: boolean;
+    constructor(config?: {
+        autoFreeze?: boolean;
+        useStrictShallowCopy?: StrictMode;
+        useStrictIteration?: boolean;
+    });
+    /**
+     * The `produce` function takes a value and a "recipe function" (whose
+     * return value often depends on the base state). The recipe function is
+     * free to mutate its first argument however it wants. All mutations are
+     * only ever applied to a __copy__ of the base state.
+     *
+     * Pass only a function to create a "curried producer" which relieves you
+     * from passing the recipe function every time.
+     *
+     * Only plain objects and arrays are made mutable. All other objects are
+     * considered uncopyable.
+     *
+     * Note: This function is __bound__ to its `Immer` instance.
+     *
+     * @param {any} base - the initial state
+     * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
+     * @param {Function} patchListener - optional function that will be called with all the patches produced here
+     * @returns {any} a new state, or the initial state if nothing was modified
+     */
+    produce: IProduce;
+    produceWithPatches: IProduceWithPatches;
+    createDraft<T extends Objectish>(base: T): Draft<T>;
+    finishDraft<D extends Draft<any>>(draft: D, patchListener?: PatchListener): D extends Draft<infer T> ? T : never;
+    /**
+     * Pass true to automatically freeze all copies created by Immer.
+     *
+     * By default, auto-freezing is enabled.
+     */
+    setAutoFreeze(value: boolean): void;
+    /**
+     * Pass true to enable strict shallow copy.
+     *
+     * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+     */
+    setUseStrictShallowCopy(value: StrictMode): void;
+    /**
+     * Pass false to use faster iteration that skips non-enumerable properties
+     * but still handles symbols for compatibility.
+     *
+     * By default, strict iteration is enabled (includes all own properties).
+     */
+    setUseStrictIteration(value: boolean): void;
+    shouldUseStrictIteration(): boolean;
+    applyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T;
+}
+
+/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */
+declare function current<T>(value: T): T;
+
+declare function enablePatches(): void;
+
+declare function enableMapSet(): void;
+
+/**
+ * Enables optimized array method handling for Immer drafts.
+ *
+ * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,
+ * significantly improving performance for array-heavy operations.
+ *
+ * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):
+ * Operate directly on the copy without creating per-element proxies.
+ *
+ * **Non-mutating methods** fall into categories:
+ * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track
+ * - **Transform operations** (concat, flat): Return base values - mutations don't track
+ * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives
+ *
+ * **Important**: Callbacks for overridden methods receive base values, not drafts.
+ * This is the core performance optimization.
+ *
+ * @example
+ * ```ts
+ * import { enableArrayMethods, produce } from "immer"
+ *
+ * enableArrayMethods()
+ *
+ * const next = produce(state, draft => {
+ *   // Optimized - no proxy creation per element
+ *   draft.items.sort((a, b) => a.value - b.value)
+ *
+ *   // filter returns drafts - mutations propagate
+ *   const filtered = draft.items.filter(x => x.value > 5)
+ *   filtered[0].value = 999 // Affects draft.items[originalIndex]
+ * })
+ * ```
+ *
+ * @see https://immerjs.github.io/immer/array-methods
+ */
+declare function enableArrayMethods(): void;
+
+/**
+ * The `produce` function takes a value and a "recipe function" (whose
+ * return value often depends on the base state). The recipe function is
+ * free to mutate its first argument however it wants. All mutations are
+ * only ever applied to a __copy__ of the base state.
+ *
+ * Pass only a function to create a "curried producer" which relieves you
+ * from passing the recipe function every time.
+ *
+ * Only plain objects and arrays are made mutable. All other objects are
+ * considered uncopyable.
+ *
+ * Note: This function is __bound__ to its `Immer` instance.
+ *
+ * @param {any} base - the initial state
+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
+ * @returns {any} a new state, or the initial state if nothing was modified
+ */
+declare const produce: IProduce;
+/**
+ * Like `produce`, but `produceWithPatches` always returns a tuple
+ * [nextState, patches, inversePatches] (instead of just the next state)
+ */
+declare const produceWithPatches: IProduceWithPatches;
+/**
+ * Pass true to automatically freeze all copies created by Immer.
+ *
+ * Always freeze by default, even in production mode
+ */
+declare const setAutoFreeze: (value: boolean) => void;
+/**
+ * Pass true to enable strict shallow copy.
+ *
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+ */
+declare const setUseStrictShallowCopy: (value: StrictMode) => void;
+/**
+ * Pass false to use loose iteration that only processes enumerable string properties.
+ * This skips symbols and non-enumerable properties for maximum performance.
+ *
+ * By default, strict iteration is enabled (includes all own properties).
+ */
+declare const setUseStrictIteration: (value: boolean) => void;
+/**
+ * Apply an array of Immer patches to the first argument.
+ *
+ * This function is a producer, which means copy-on-write is in effect.
+ */
+declare const applyPatches: <T extends Objectish>(base: T, patches: readonly Patch[]) => T;
+/**
+ * Create an Immer draft from the given base state, which may be a draft itself.
+ * The draft can be modified until you finalize it with the `finishDraft` function.
+ */
+declare const createDraft: <T extends Objectish>(base: T) => Draft<T>;
+/**
+ * Finalize an Immer draft from a `createDraft` call, returning the base state
+ * (if no changes were made) or a modified copy. The draft must *not* be
+ * mutated afterwards.
+ *
+ * Pass a function as the 2nd argument to generate Immer patches based on the
+ * changes that were made.
+ */
+declare const finishDraft: <D extends unknown>(draft: D, patchListener?: PatchListener | undefined) => D extends Draft<infer T> ? T : never;
+/**
+ * This function is actually a no-op, but can be used to cast an immutable type
+ * to an draft type and make TypeScript happy
+ *
+ * @param value
+ */
+declare let castDraft: <T>(value: T) => Draft<T>;
+/**
+ * This function is actually a no-op, but can be used to cast a mutable type
+ * to an immutable type and make TypeScript happy
+ * @param value
+ */
+declare let castImmutable: <T>(value: T) => Immutable<T>;
+
+export { Draft, Immer, Immutable, Objectish, Patch, PatchListener, Producer, StrictMode, WritableDraft, applyPatches, castDraft, castImmutable, createDraft, current, enableArrayMethods, enableMapSet, enablePatches, finishDraft, freeze, DRAFTABLE as immerable, isDraft, isDraftable, NOTHING as nothing, original, produce, produceWithPatches, setAutoFreeze, setUseStrictIteration, setUseStrictShallowCopy };
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.legacy-esm.js
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.legacy-esm.js	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1672 @@
+var __defProp = Object.defineProperty;
+var __getOwnPropSymbols = Object.getOwnPropertySymbols;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __propIsEnum = Object.prototype.propertyIsEnumerable;
+var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __spreadValues = (a, b) => {
+  for (var prop in b || (b = {}))
+    if (__hasOwnProp.call(b, prop))
+      __defNormalProp(a, prop, b[prop]);
+  if (__getOwnPropSymbols)
+    for (var prop of __getOwnPropSymbols(b)) {
+      if (__propIsEnum.call(b, prop))
+        __defNormalProp(a, prop, b[prop]);
+    }
+  return a;
+};
+
+// src/utils/env.ts
+var NOTHING = Symbol.for("immer-nothing");
+var DRAFTABLE = Symbol.for("immer-draftable");
+var DRAFT_STATE = Symbol.for("immer-state");
+
+// src/utils/errors.ts
+var errors = process.env.NODE_ENV !== "production" ? [
+  // All error codes, starting by 0:
+  function(plugin) {
+    return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
+  },
+  function(thing) {
+    return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
+  },
+  "This object has been frozen and should not be mutated",
+  function(data) {
+    return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
+  },
+  "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
+  "Immer forbids circular references",
+  "The first or second argument to `produce` must be a function",
+  "The third argument to `produce` must be a function or undefined",
+  "First argument to `createDraft` must be a plain object, an array, or an immerable object",
+  "First argument to `finishDraft` must be a draft returned by `createDraft`",
+  function(thing) {
+    return `'current' expects a draft, got: ${thing}`;
+  },
+  "Object.defineProperty() cannot be used on an Immer draft",
+  "Object.setPrototypeOf() cannot be used on an Immer draft",
+  "Immer only supports deleting array indices",
+  "Immer only supports setting array indices and the 'length' property",
+  function(thing) {
+    return `'original' expects a draft, got: ${thing}`;
+  }
+  // Note: if more errors are added, the errorOffset in Patches.ts should be increased
+  // See Patches.ts for additional errors
+] : [];
+function die(error, ...args) {
+  if (process.env.NODE_ENV !== "production") {
+    const e = errors[error];
+    const msg = isFunction(e) ? e.apply(null, args) : e;
+    throw new Error(`[Immer] ${msg}`);
+  }
+  throw new Error(
+    `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
+  );
+}
+
+// src/utils/common.ts
+var O = Object;
+var getPrototypeOf = O.getPrototypeOf;
+var CONSTRUCTOR = "constructor";
+var PROTOTYPE = "prototype";
+var CONFIGURABLE = "configurable";
+var ENUMERABLE = "enumerable";
+var WRITABLE = "writable";
+var VALUE = "value";
+var isDraft = (value) => !!value && !!value[DRAFT_STATE];
+function isDraftable(value) {
+  var _a;
+  if (!value)
+    return false;
+  return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!((_a = value[CONSTRUCTOR]) == null ? void 0 : _a[DRAFTABLE]) || isMap(value) || isSet(value);
+}
+var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
+var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
+function isPlainObject(value) {
+  if (!value || !isObjectish(value))
+    return false;
+  const proto = getPrototypeOf(value);
+  if (proto === null || proto === O[PROTOTYPE])
+    return true;
+  const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
+  if (Ctor === Object)
+    return true;
+  if (!isFunction(Ctor))
+    return false;
+  let ctorString = cachedCtorStrings.get(Ctor);
+  if (ctorString === void 0) {
+    ctorString = Function.toString.call(Ctor);
+    cachedCtorStrings.set(Ctor, ctorString);
+  }
+  return ctorString === objectCtorString;
+}
+function original(value) {
+  if (!isDraft(value))
+    die(15, value);
+  return value[DRAFT_STATE].base_;
+}
+function each(obj, iter, strict = true) {
+  if (getArchtype(obj) === 0 /* Object */) {
+    const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
+    keys.forEach((key) => {
+      iter(key, obj[key], obj);
+    });
+  } else {
+    obj.forEach((entry, index) => iter(index, entry, obj));
+  }
+}
+function getArchtype(thing) {
+  const state = thing[DRAFT_STATE];
+  return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
+}
+var has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
+var get = (thing, prop, type = getArchtype(thing)) => (
+  // @ts-ignore
+  type === 2 /* Map */ ? thing.get(prop) : thing[prop]
+);
+var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
+  if (type === 2 /* Map */)
+    thing.set(propOrOldValue, value);
+  else if (type === 3 /* Set */) {
+    thing.add(value);
+  } else
+    thing[propOrOldValue] = value;
+};
+function is(x, y) {
+  if (x === y) {
+    return x !== 0 || 1 / x === 1 / y;
+  } else {
+    return x !== x && y !== y;
+  }
+}
+var isArray = Array.isArray;
+var isMap = (target) => target instanceof Map;
+var isSet = (target) => target instanceof Set;
+var isObjectish = (target) => typeof target === "object";
+var isFunction = (target) => typeof target === "function";
+var isBoolean = (target) => typeof target === "boolean";
+function isArrayIndex(value) {
+  const n = +value;
+  return Number.isInteger(n) && String(n) === value;
+}
+var getProxyDraft = (value) => {
+  if (!isObjectish(value))
+    return null;
+  return value == null ? void 0 : value[DRAFT_STATE];
+};
+var latest = (state) => state.copy_ || state.base_;
+var getValue = (value) => {
+  var _a;
+  const proxyDraft = getProxyDraft(value);
+  return proxyDraft ? (_a = proxyDraft.copy_) != null ? _a : proxyDraft.base_ : value;
+};
+var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
+function shallowCopy(base, strict) {
+  if (isMap(base)) {
+    return new Map(base);
+  }
+  if (isSet(base)) {
+    return new Set(base);
+  }
+  if (isArray(base))
+    return Array[PROTOTYPE].slice.call(base);
+  const isPlain = isPlainObject(base);
+  if (strict === true || strict === "class_only" && !isPlain) {
+    const descriptors = O.getOwnPropertyDescriptors(base);
+    delete descriptors[DRAFT_STATE];
+    let keys = Reflect.ownKeys(descriptors);
+    for (let i = 0; i < keys.length; i++) {
+      const key = keys[i];
+      const desc = descriptors[key];
+      if (desc[WRITABLE] === false) {
+        desc[WRITABLE] = true;
+        desc[CONFIGURABLE] = true;
+      }
+      if (desc.get || desc.set)
+        descriptors[key] = {
+          [CONFIGURABLE]: true,
+          [WRITABLE]: true,
+          // could live with !!desc.set as well here...
+          [ENUMERABLE]: desc[ENUMERABLE],
+          [VALUE]: base[key]
+        };
+    }
+    return O.create(getPrototypeOf(base), descriptors);
+  } else {
+    const proto = getPrototypeOf(base);
+    if (proto !== null && isPlain) {
+      return __spreadValues({}, base);
+    }
+    const obj = O.create(proto);
+    return O.assign(obj, base);
+  }
+}
+function freeze(obj, deep = false) {
+  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
+    return obj;
+  if (getArchtype(obj) > 1) {
+    O.defineProperties(obj, {
+      set: dontMutateMethodOverride,
+      add: dontMutateMethodOverride,
+      clear: dontMutateMethodOverride,
+      delete: dontMutateMethodOverride
+    });
+  }
+  O.freeze(obj);
+  if (deep)
+    each(
+      obj,
+      (_key, value) => {
+        freeze(value, true);
+      },
+      false
+    );
+  return obj;
+}
+function dontMutateFrozenCollections() {
+  die(2);
+}
+var dontMutateMethodOverride = {
+  [VALUE]: dontMutateFrozenCollections
+};
+function isFrozen(obj) {
+  if (obj === null || !isObjectish(obj))
+    return true;
+  return O.isFrozen(obj);
+}
+
+// src/utils/plugins.ts
+var PluginMapSet = "MapSet";
+var PluginPatches = "Patches";
+var PluginArrayMethods = "ArrayMethods";
+var plugins = {};
+function getPlugin(pluginKey) {
+  const plugin = plugins[pluginKey];
+  if (!plugin) {
+    die(0, pluginKey);
+  }
+  return plugin;
+}
+var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
+function loadPlugin(pluginKey, implementation) {
+  if (!plugins[pluginKey])
+    plugins[pluginKey] = implementation;
+}
+
+// src/core/scope.ts
+var currentScope;
+var getCurrentScope = () => currentScope;
+var createScope = (parent_, immer_) => ({
+  drafts_: [],
+  parent_,
+  immer_,
+  // Whenever the modified draft contains a draft from another scope, we
+  // need to prevent auto-freezing so the unowned draft can be finalized.
+  canAutoFreeze_: true,
+  unfinalizedDrafts_: 0,
+  handledSet_: /* @__PURE__ */ new Set(),
+  processedForPatches_: /* @__PURE__ */ new Set(),
+  mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
+  arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
+});
+function usePatchesInScope(scope, patchListener) {
+  if (patchListener) {
+    scope.patchPlugin_ = getPlugin(PluginPatches);
+    scope.patches_ = [];
+    scope.inversePatches_ = [];
+    scope.patchListener_ = patchListener;
+  }
+}
+function revokeScope(scope) {
+  leaveScope(scope);
+  scope.drafts_.forEach(revokeDraft);
+  scope.drafts_ = null;
+}
+function leaveScope(scope) {
+  if (scope === currentScope) {
+    currentScope = scope.parent_;
+  }
+}
+var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
+function revokeDraft(draft) {
+  const state = draft[DRAFT_STATE];
+  if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
+    state.revoke_();
+  else
+    state.revoked_ = true;
+}
+
+// src/core/finalize.ts
+function processResult(result, scope) {
+  scope.unfinalizedDrafts_ = scope.drafts_.length;
+  const baseDraft = scope.drafts_[0];
+  const isReplaced = result !== void 0 && result !== baseDraft;
+  if (isReplaced) {
+    if (baseDraft[DRAFT_STATE].modified_) {
+      revokeScope(scope);
+      die(4);
+    }
+    if (isDraftable(result)) {
+      result = finalize(scope, result);
+    }
+    const { patchPlugin_ } = scope;
+    if (patchPlugin_) {
+      patchPlugin_.generateReplacementPatches_(
+        baseDraft[DRAFT_STATE].base_,
+        result,
+        scope
+      );
+    }
+  } else {
+    result = finalize(scope, baseDraft);
+  }
+  maybeFreeze(scope, result, true);
+  revokeScope(scope);
+  if (scope.patches_) {
+    scope.patchListener_(scope.patches_, scope.inversePatches_);
+  }
+  return result !== NOTHING ? result : void 0;
+}
+function finalize(rootScope, value) {
+  if (isFrozen(value))
+    return value;
+  const state = value[DRAFT_STATE];
+  if (!state) {
+    const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
+    return finalValue;
+  }
+  if (!isSameScope(state, rootScope)) {
+    return value;
+  }
+  if (!state.modified_) {
+    return state.base_;
+  }
+  if (!state.finalized_) {
+    const { callbacks_ } = state;
+    if (callbacks_) {
+      while (callbacks_.length > 0) {
+        const callback = callbacks_.pop();
+        callback(rootScope);
+      }
+    }
+    generatePatchesAndFinalize(state, rootScope);
+  }
+  return state.copy_;
+}
+function maybeFreeze(scope, value, deep = false) {
+  if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
+    freeze(value, deep);
+  }
+}
+function markStateFinalized(state) {
+  state.finalized_ = true;
+  state.scope_.unfinalizedDrafts_--;
+}
+var isSameScope = (state, rootScope) => state.scope_ === rootScope;
+var EMPTY_LOCATIONS_RESULT = [];
+function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
+  var _a;
+  const parentCopy = latest(parent);
+  const parentType = parent.type_;
+  if (originalKey !== void 0) {
+    const currentValue = get(parentCopy, originalKey, parentType);
+    if (currentValue === draftValue) {
+      set(parentCopy, originalKey, finalizedValue, parentType);
+      return;
+    }
+  }
+  if (!parent.draftLocations_) {
+    const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
+    each(parentCopy, (key, value) => {
+      if (isDraft(value)) {
+        const keys = draftLocations.get(value) || [];
+        keys.push(key);
+        draftLocations.set(value, keys);
+      }
+    });
+  }
+  const locations = (_a = parent.draftLocations_.get(draftValue)) != null ? _a : EMPTY_LOCATIONS_RESULT;
+  for (const location of locations) {
+    set(parentCopy, location, finalizedValue, parentType);
+  }
+}
+function registerChildFinalizationCallback(parent, child, key) {
+  parent.callbacks_.push(function childCleanup(rootScope) {
+    var _a, _b;
+    const state = child;
+    if (!state || !isSameScope(state, rootScope)) {
+      return;
+    }
+    (_a = rootScope.mapSetPlugin_) == null ? void 0 : _a.fixSetContents(state);
+    const finalizedValue = getFinalValue(state);
+    updateDraftInParent(parent, (_b = state.draft_) != null ? _b : state, finalizedValue, key);
+    generatePatchesAndFinalize(state, rootScope);
+  });
+}
+function generatePatchesAndFinalize(state, rootScope) {
+  var _a, _b;
+  const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || ((_b = (_a = state.assigned_) == null ? void 0 : _a.size) != null ? _b : 0) > 0);
+  if (shouldFinalize) {
+    const { patchPlugin_ } = rootScope;
+    if (patchPlugin_) {
+      const basePath = patchPlugin_.getPath(state);
+      if (basePath) {
+        patchPlugin_.generatePatches_(state, basePath, rootScope);
+      }
+    }
+    markStateFinalized(state);
+  }
+}
+function handleCrossReference(target, key, value) {
+  const { scope_ } = target;
+  if (isDraft(value)) {
+    const state = value[DRAFT_STATE];
+    if (isSameScope(state, scope_)) {
+      state.callbacks_.push(function crossReferenceCleanup() {
+        prepareCopy(target);
+        const finalizedValue = getFinalValue(state);
+        updateDraftInParent(target, value, finalizedValue, key);
+      });
+    }
+  } else if (isDraftable(value)) {
+    target.callbacks_.push(function nestedDraftCleanup() {
+      var _a;
+      const targetCopy = latest(target);
+      if (target.type_ === 3 /* Set */) {
+        if (targetCopy.has(value)) {
+          handleValue(value, scope_.handledSet_, scope_);
+        }
+      } else {
+        if (get(targetCopy, key, target.type_) === value) {
+          if (scope_.drafts_.length > 1 && ((_a = target.assigned_.get(key)) != null ? _a : false) === true && target.copy_) {
+            handleValue(
+              get(target.copy_, key, target.type_),
+              scope_.handledSet_,
+              scope_
+            );
+          }
+        }
+      }
+    });
+  }
+}
+function handleValue(target, handledSet, rootScope) {
+  if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
+    return target;
+  }
+  if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
+    return target;
+  }
+  handledSet.add(target);
+  each(target, (key, value) => {
+    if (isDraft(value)) {
+      const state = value[DRAFT_STATE];
+      if (isSameScope(state, rootScope)) {
+        const updatedValue = getFinalValue(state);
+        set(target, key, updatedValue, target.type_);
+        markStateFinalized(state);
+      }
+    } else if (isDraftable(value)) {
+      handleValue(value, handledSet, rootScope);
+    }
+  });
+  return target;
+}
+
+// src/core/proxy.ts
+function createProxyProxy(base, parent) {
+  const baseIsArray = isArray(base);
+  const state = {
+    type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,
+    // Track which produce call this is associated with.
+    scope_: parent ? parent.scope_ : getCurrentScope(),
+    // True for both shallow and deep changes.
+    modified_: false,
+    // Used during finalization.
+    finalized_: false,
+    // Track which properties have been assigned (true) or deleted (false).
+    // actually instantiated in `prepareCopy()`
+    assigned_: void 0,
+    // The parent draft state.
+    parent_: parent,
+    // The base state.
+    base_: base,
+    // The base proxy.
+    draft_: null,
+    // set below
+    // The base copy with any updated values.
+    copy_: null,
+    // Called by the `produce` function.
+    revoke_: null,
+    isManual_: false,
+    // `callbacks` actually gets assigned in `createProxy`
+    callbacks_: void 0
+  };
+  let target = state;
+  let traps = objectTraps;
+  if (baseIsArray) {
+    target = [state];
+    traps = arrayTraps;
+  }
+  const { revoke, proxy } = Proxy.revocable(target, traps);
+  state.draft_ = proxy;
+  state.revoke_ = revoke;
+  return [proxy, state];
+}
+var objectTraps = {
+  get(state, prop) {
+    if (prop === DRAFT_STATE)
+      return state;
+    let arrayPlugin = state.scope_.arrayMethodsPlugin_;
+    const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === "string";
+    if (isArrayWithStringProp) {
+      if (arrayPlugin == null ? void 0 : arrayPlugin.isArrayOperationMethod(prop)) {
+        return arrayPlugin.createMethodInterceptor(state, prop);
+      }
+    }
+    const source = latest(state);
+    if (!has(source, prop, state.type_)) {
+      return readPropFromProto(state, source, prop);
+    }
+    const value = source[prop];
+    if (state.finalized_ || !isDraftable(value)) {
+      return value;
+    }
+    if (isArrayWithStringProp && state.operationMethod && (arrayPlugin == null ? void 0 : arrayPlugin.isMutatingArrayMethod(
+      state.operationMethod
+    )) && isArrayIndex(prop)) {
+      return value;
+    }
+    if (value === peek(state.base_, prop)) {
+      prepareCopy(state);
+      const childKey = state.type_ === 1 /* Array */ ? +prop : prop;
+      const childDraft = createProxy(state.scope_, value, state, childKey);
+      return state.copy_[childKey] = childDraft;
+    }
+    return value;
+  },
+  has(state, prop) {
+    return prop in latest(state);
+  },
+  ownKeys(state) {
+    return Reflect.ownKeys(latest(state));
+  },
+  set(state, prop, value) {
+    const desc = getDescriptorFromProto(latest(state), prop);
+    if (desc == null ? void 0 : desc.set) {
+      desc.set.call(state.draft_, value);
+      return true;
+    }
+    if (!state.modified_) {
+      const current2 = peek(latest(state), prop);
+      const currentState = current2 == null ? void 0 : current2[DRAFT_STATE];
+      if (currentState && currentState.base_ === value) {
+        state.copy_[prop] = value;
+        state.assigned_.set(prop, false);
+        return true;
+      }
+      if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))
+        return true;
+      prepareCopy(state);
+      markChanged(state);
+    }
+    if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
+    (value !== void 0 || prop in state.copy_) || // special case: NaN
+    Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
+      return true;
+    state.copy_[prop] = value;
+    state.assigned_.set(prop, true);
+    handleCrossReference(state, prop, value);
+    return true;
+  },
+  deleteProperty(state, prop) {
+    prepareCopy(state);
+    if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
+      state.assigned_.set(prop, false);
+      markChanged(state);
+    } else {
+      state.assigned_.delete(prop);
+    }
+    if (state.copy_) {
+      delete state.copy_[prop];
+    }
+    return true;
+  },
+  // Note: We never coerce `desc.value` into an Immer draft, because we can't make
+  // the same guarantee in ES5 mode.
+  getOwnPropertyDescriptor(state, prop) {
+    const owner = latest(state);
+    const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
+    if (!desc)
+      return desc;
+    return {
+      [WRITABLE]: true,
+      [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== "length",
+      [ENUMERABLE]: desc[ENUMERABLE],
+      [VALUE]: owner[prop]
+    };
+  },
+  defineProperty() {
+    die(11);
+  },
+  getPrototypeOf(state) {
+    return getPrototypeOf(state.base_);
+  },
+  setPrototypeOf() {
+    die(12);
+  }
+};
+var arrayTraps = {};
+for (let key in objectTraps) {
+  let fn = objectTraps[key];
+  arrayTraps[key] = function() {
+    const args = arguments;
+    args[0] = args[0][0];
+    return fn.apply(this, args);
+  };
+}
+arrayTraps.deleteProperty = function(state, prop) {
+  if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
+    die(13);
+  return arrayTraps.set.call(this, state, prop, void 0);
+};
+arrayTraps.set = function(state, prop, value) {
+  if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
+    die(14);
+  return objectTraps.set.call(this, state[0], prop, value, state[0]);
+};
+function peek(draft, prop) {
+  const state = draft[DRAFT_STATE];
+  const source = state ? latest(state) : draft;
+  return source[prop];
+}
+function readPropFromProto(state, source, prop) {
+  var _a;
+  const desc = getDescriptorFromProto(source, prop);
+  return desc ? VALUE in desc ? desc[VALUE] : (
+    // This is a very special case, if the prop is a getter defined by the
+    // prototype, we should invoke it with the draft as context!
+    (_a = desc.get) == null ? void 0 : _a.call(state.draft_)
+  ) : void 0;
+}
+function getDescriptorFromProto(source, prop) {
+  if (!(prop in source))
+    return void 0;
+  let proto = getPrototypeOf(source);
+  while (proto) {
+    const desc = Object.getOwnPropertyDescriptor(proto, prop);
+    if (desc)
+      return desc;
+    proto = getPrototypeOf(proto);
+  }
+  return void 0;
+}
+function markChanged(state) {
+  if (!state.modified_) {
+    state.modified_ = true;
+    if (state.parent_) {
+      markChanged(state.parent_);
+    }
+  }
+}
+function prepareCopy(state) {
+  if (!state.copy_) {
+    state.assigned_ = /* @__PURE__ */ new Map();
+    state.copy_ = shallowCopy(
+      state.base_,
+      state.scope_.immer_.useStrictShallowCopy_
+    );
+  }
+}
+
+// src/core/immerClass.ts
+var Immer2 = class {
+  constructor(config) {
+    this.autoFreeze_ = true;
+    this.useStrictShallowCopy_ = false;
+    this.useStrictIteration_ = false;
+    /**
+     * The `produce` function takes a value and a "recipe function" (whose
+     * return value often depends on the base state). The recipe function is
+     * free to mutate its first argument however it wants. All mutations are
+     * only ever applied to a __copy__ of the base state.
+     *
+     * Pass only a function to create a "curried producer" which relieves you
+     * from passing the recipe function every time.
+     *
+     * Only plain objects and arrays are made mutable. All other objects are
+     * considered uncopyable.
+     *
+     * Note: This function is __bound__ to its `Immer` instance.
+     *
+     * @param {any} base - the initial state
+     * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
+     * @param {Function} patchListener - optional function that will be called with all the patches produced here
+     * @returns {any} a new state, or the initial state if nothing was modified
+     */
+    this.produce = (base, recipe, patchListener) => {
+      if (isFunction(base) && !isFunction(recipe)) {
+        const defaultBase = recipe;
+        recipe = base;
+        const self = this;
+        return function curriedProduce(base2 = defaultBase, ...args) {
+          return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
+        };
+      }
+      if (!isFunction(recipe))
+        die(6);
+      if (patchListener !== void 0 && !isFunction(patchListener))
+        die(7);
+      let result;
+      if (isDraftable(base)) {
+        const scope = enterScope(this);
+        const proxy = createProxy(scope, base, void 0);
+        let hasError = true;
+        try {
+          result = recipe(proxy);
+          hasError = false;
+        } finally {
+          if (hasError)
+            revokeScope(scope);
+          else
+            leaveScope(scope);
+        }
+        usePatchesInScope(scope, patchListener);
+        return processResult(result, scope);
+      } else if (!base || !isObjectish(base)) {
+        result = recipe(base);
+        if (result === void 0)
+          result = base;
+        if (result === NOTHING)
+          result = void 0;
+        if (this.autoFreeze_)
+          freeze(result, true);
+        if (patchListener) {
+          const p = [];
+          const ip = [];
+          getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
+            patches_: p,
+            inversePatches_: ip
+          });
+          patchListener(p, ip);
+        }
+        return result;
+      } else
+        die(1, base);
+    };
+    this.produceWithPatches = (base, recipe) => {
+      if (isFunction(base)) {
+        return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
+      }
+      let patches, inversePatches;
+      const result = this.produce(base, recipe, (p, ip) => {
+        patches = p;
+        inversePatches = ip;
+      });
+      return [result, patches, inversePatches];
+    };
+    if (isBoolean(config == null ? void 0 : config.autoFreeze))
+      this.setAutoFreeze(config.autoFreeze);
+    if (isBoolean(config == null ? void 0 : config.useStrictShallowCopy))
+      this.setUseStrictShallowCopy(config.useStrictShallowCopy);
+    if (isBoolean(config == null ? void 0 : config.useStrictIteration))
+      this.setUseStrictIteration(config.useStrictIteration);
+  }
+  createDraft(base) {
+    if (!isDraftable(base))
+      die(8);
+    if (isDraft(base))
+      base = current(base);
+    const scope = enterScope(this);
+    const proxy = createProxy(scope, base, void 0);
+    proxy[DRAFT_STATE].isManual_ = true;
+    leaveScope(scope);
+    return proxy;
+  }
+  finishDraft(draft, patchListener) {
+    const state = draft && draft[DRAFT_STATE];
+    if (!state || !state.isManual_)
+      die(9);
+    const { scope_: scope } = state;
+    usePatchesInScope(scope, patchListener);
+    return processResult(void 0, scope);
+  }
+  /**
+   * Pass true to automatically freeze all copies created by Immer.
+   *
+   * By default, auto-freezing is enabled.
+   */
+  setAutoFreeze(value) {
+    this.autoFreeze_ = value;
+  }
+  /**
+   * Pass true to enable strict shallow copy.
+   *
+   * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+   */
+  setUseStrictShallowCopy(value) {
+    this.useStrictShallowCopy_ = value;
+  }
+  /**
+   * Pass false to use faster iteration that skips non-enumerable properties
+   * but still handles symbols for compatibility.
+   *
+   * By default, strict iteration is enabled (includes all own properties).
+   */
+  setUseStrictIteration(value) {
+    this.useStrictIteration_ = value;
+  }
+  shouldUseStrictIteration() {
+    return this.useStrictIteration_;
+  }
+  applyPatches(base, patches) {
+    let i;
+    for (i = patches.length - 1; i >= 0; i--) {
+      const patch = patches[i];
+      if (patch.path.length === 0 && patch.op === "replace") {
+        base = patch.value;
+        break;
+      }
+    }
+    if (i > -1) {
+      patches = patches.slice(i + 1);
+    }
+    const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
+    if (isDraft(base)) {
+      return applyPatchesImpl(base, patches);
+    }
+    return this.produce(
+      base,
+      (draft) => applyPatchesImpl(draft, patches)
+    );
+  }
+};
+function createProxy(rootScope, value, parent, key) {
+  var _a, _b;
+  const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
+  const scope = (_a = parent == null ? void 0 : parent.scope_) != null ? _a : getCurrentScope();
+  scope.drafts_.push(draft);
+  state.callbacks_ = (_b = parent == null ? void 0 : parent.callbacks_) != null ? _b : [];
+  state.key_ = key;
+  if (parent && key !== void 0) {
+    registerChildFinalizationCallback(parent, state, key);
+  } else {
+    state.callbacks_.push(function rootDraftCleanup(rootScope2) {
+      var _a2;
+      (_a2 = rootScope2.mapSetPlugin_) == null ? void 0 : _a2.fixSetContents(state);
+      const { patchPlugin_ } = rootScope2;
+      if (state.modified_ && patchPlugin_) {
+        patchPlugin_.generatePatches_(state, [], rootScope2);
+      }
+    });
+  }
+  return draft;
+}
+
+// src/core/current.ts
+function current(value) {
+  if (!isDraft(value))
+    die(10, value);
+  return currentImpl(value);
+}
+function currentImpl(value) {
+  if (!isDraftable(value) || isFrozen(value))
+    return value;
+  const state = value[DRAFT_STATE];
+  let copy;
+  let strict = true;
+  if (state) {
+    if (!state.modified_)
+      return state.base_;
+    state.finalized_ = true;
+    copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
+    strict = state.scope_.immer_.shouldUseStrictIteration();
+  } else {
+    copy = shallowCopy(value, true);
+  }
+  each(
+    copy,
+    (key, childValue) => {
+      set(copy, key, currentImpl(childValue));
+    },
+    strict
+  );
+  if (state) {
+    state.finalized_ = false;
+  }
+  return copy;
+}
+
+// src/plugins/patches.ts
+function enablePatches() {
+  const errorOffset = 16;
+  if (process.env.NODE_ENV !== "production") {
+    errors.push(
+      'Sets cannot have "replace" patches.',
+      function(op) {
+        return "Unsupported patch operation: " + op;
+      },
+      function(path) {
+        return "Cannot apply patch, path doesn't resolve: " + path;
+      },
+      "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
+    );
+  }
+  function getPath(state, path = []) {
+    var _a;
+    if (state.key_ !== void 0) {
+      const parentCopy = (_a = state.parent_.copy_) != null ? _a : state.parent_.base_;
+      const proxyDraft = getProxyDraft(get(parentCopy, state.key_));
+      const valueAtKey = get(parentCopy, state.key_);
+      if (valueAtKey === void 0) {
+        return null;
+      }
+      if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {
+        return null;
+      }
+      if (proxyDraft != null && proxyDraft.base_ !== state.base_) {
+        return null;
+      }
+      const isSet2 = state.parent_.type_ === 3 /* Set */;
+      let key;
+      if (isSet2) {
+        const setParent = state.parent_;
+        key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);
+      } else {
+        key = state.key_;
+      }
+      if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {
+        return null;
+      }
+      path.push(key);
+    }
+    if (state.parent_) {
+      return getPath(state.parent_, path);
+    }
+    path.reverse();
+    try {
+      resolvePath(state.copy_, path);
+    } catch (e) {
+      return null;
+    }
+    return path;
+  }
+  function resolvePath(base, path) {
+    let current2 = base;
+    for (let i = 0; i < path.length - 1; i++) {
+      const key = path[i];
+      current2 = get(current2, key);
+      if (!isObjectish(current2) || current2 === null) {
+        throw new Error(`Cannot resolve path at '${path.join("/")}'`);
+      }
+    }
+    return current2;
+  }
+  const REPLACE = "replace";
+  const ADD = "add";
+  const REMOVE = "remove";
+  function generatePatches_(state, basePath, scope) {
+    if (state.scope_.processedForPatches_.has(state)) {
+      return;
+    }
+    state.scope_.processedForPatches_.add(state);
+    const { patches_, inversePatches_ } = scope;
+    switch (state.type_) {
+      case 0 /* Object */:
+      case 2 /* Map */:
+        return generatePatchesFromAssigned(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+      case 1 /* Array */:
+        return generateArrayPatches(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+      case 3 /* Set */:
+        return generateSetPatches(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+    }
+  }
+  function generateArrayPatches(state, basePath, patches, inversePatches) {
+    let { base_, assigned_ } = state;
+    let copy_ = state.copy_;
+    if (copy_.length < base_.length) {
+      ;
+      [base_, copy_] = [copy_, base_];
+      [patches, inversePatches] = [inversePatches, patches];
+    }
+    const allReassigned = state.allIndicesReassigned_ === true;
+    for (let i = 0; i < base_.length; i++) {
+      const copiedItem = copy_[i];
+      const baseItem = base_[i];
+      const isAssigned = allReassigned || (assigned_ == null ? void 0 : assigned_.get(i.toString()));
+      if (isAssigned && copiedItem !== baseItem) {
+        const childState = copiedItem == null ? void 0 : copiedItem[DRAFT_STATE];
+        if (childState && childState.modified_) {
+          continue;
+        }
+        const path = basePath.concat([i]);
+        patches.push({
+          op: REPLACE,
+          path,
+          // Need to maybe clone it, as it can in fact be the original value
+          // due to the base/copy inversion at the start of this function
+          value: clonePatchValueIfNeeded(copiedItem)
+        });
+        inversePatches.push({
+          op: REPLACE,
+          path,
+          value: clonePatchValueIfNeeded(baseItem)
+        });
+      }
+    }
+    for (let i = base_.length; i < copy_.length; i++) {
+      const path = basePath.concat([i]);
+      patches.push({
+        op: ADD,
+        path,
+        // Need to maybe clone it, as it can in fact be the original value
+        // due to the base/copy inversion at the start of this function
+        value: clonePatchValueIfNeeded(copy_[i])
+      });
+    }
+    for (let i = copy_.length - 1; base_.length <= i; --i) {
+      const path = basePath.concat([i]);
+      inversePatches.push({
+        op: REMOVE,
+        path
+      });
+    }
+  }
+  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
+    const { base_, copy_, type_ } = state;
+    each(state.assigned_, (key, assignedValue) => {
+      const origValue = get(base_, key, type_);
+      const value = get(copy_, key, type_);
+      const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
+      if (origValue === value && op === REPLACE)
+        return;
+      const path = basePath.concat(key);
+      patches.push(
+        op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }
+      );
+      inversePatches.push(
+        op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
+      );
+    });
+  }
+  function generateSetPatches(state, basePath, patches, inversePatches) {
+    let { base_, copy_ } = state;
+    let i = 0;
+    base_.forEach((value) => {
+      if (!copy_.has(value)) {
+        const path = basePath.concat([i]);
+        patches.push({
+          op: REMOVE,
+          path,
+          value
+        });
+        inversePatches.unshift({
+          op: ADD,
+          path,
+          value
+        });
+      }
+      i++;
+    });
+    i = 0;
+    copy_.forEach((value) => {
+      if (!base_.has(value)) {
+        const path = basePath.concat([i]);
+        patches.push({
+          op: ADD,
+          path,
+          value
+        });
+        inversePatches.unshift({
+          op: REMOVE,
+          path,
+          value
+        });
+      }
+      i++;
+    });
+  }
+  function generateReplacementPatches_(baseValue, replacement, scope) {
+    const { patches_, inversePatches_ } = scope;
+    patches_.push({
+      op: REPLACE,
+      path: [],
+      value: replacement === NOTHING ? void 0 : replacement
+    });
+    inversePatches_.push({
+      op: REPLACE,
+      path: [],
+      value: baseValue
+    });
+  }
+  function applyPatches_(draft, patches) {
+    patches.forEach((patch) => {
+      const { path, op } = patch;
+      let base = draft;
+      for (let i = 0; i < path.length - 1; i++) {
+        const parentType = getArchtype(base);
+        let p = path[i];
+        if (typeof p !== "string" && typeof p !== "number") {
+          p = "" + p;
+        }
+        if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === CONSTRUCTOR))
+          die(errorOffset + 3);
+        if (isFunction(base) && p === PROTOTYPE)
+          die(errorOffset + 3);
+        base = get(base, p);
+        if (!isObjectish(base))
+          die(errorOffset + 2, path.join("/"));
+      }
+      const type = getArchtype(base);
+      const value = deepClonePatchValue(patch.value);
+      const key = path[path.length - 1];
+      switch (op) {
+        case REPLACE:
+          switch (type) {
+            case 2 /* Map */:
+              return base.set(key, value);
+            case 3 /* Set */:
+              die(errorOffset);
+            default:
+              return base[key] = value;
+          }
+        case ADD:
+          switch (type) {
+            case 1 /* Array */:
+              return key === "-" ? base.push(value) : base.splice(key, 0, value);
+            case 2 /* Map */:
+              return base.set(key, value);
+            case 3 /* Set */:
+              return base.add(value);
+            default:
+              return base[key] = value;
+          }
+        case REMOVE:
+          switch (type) {
+            case 1 /* Array */:
+              return base.splice(key, 1);
+            case 2 /* Map */:
+              return base.delete(key);
+            case 3 /* Set */:
+              return base.delete(patch.value);
+            default:
+              return delete base[key];
+          }
+        default:
+          die(errorOffset + 1, op);
+      }
+    });
+    return draft;
+  }
+  function deepClonePatchValue(obj) {
+    if (!isDraftable(obj))
+      return obj;
+    if (isArray(obj))
+      return obj.map(deepClonePatchValue);
+    if (isMap(obj))
+      return new Map(
+        Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
+      );
+    if (isSet(obj))
+      return new Set(Array.from(obj).map(deepClonePatchValue));
+    const cloned = Object.create(getPrototypeOf(obj));
+    for (const key in obj)
+      cloned[key] = deepClonePatchValue(obj[key]);
+    if (has(obj, DRAFTABLE))
+      cloned[DRAFTABLE] = obj[DRAFTABLE];
+    return cloned;
+  }
+  function clonePatchValueIfNeeded(obj) {
+    if (isDraft(obj)) {
+      return deepClonePatchValue(obj);
+    } else
+      return obj;
+  }
+  loadPlugin(PluginPatches, {
+    applyPatches_,
+    generatePatches_,
+    generateReplacementPatches_,
+    getPath
+  });
+}
+
+// src/plugins/mapset.ts
+function enableMapSet() {
+  class DraftMap extends Map {
+    constructor(target, parent) {
+      super();
+      this[DRAFT_STATE] = {
+        type_: 2 /* Map */,
+        parent_: parent,
+        scope_: parent ? parent.scope_ : getCurrentScope(),
+        modified_: false,
+        finalized_: false,
+        copy_: void 0,
+        assigned_: void 0,
+        base_: target,
+        draft_: this,
+        isManual_: false,
+        revoked_: false,
+        callbacks_: []
+      };
+    }
+    get size() {
+      return latest(this[DRAFT_STATE]).size;
+    }
+    has(key) {
+      return latest(this[DRAFT_STATE]).has(key);
+    }
+    set(key, value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!latest(state).has(key) || latest(state).get(key) !== value) {
+        prepareMapCopy(state);
+        markChanged(state);
+        state.assigned_.set(key, true);
+        state.copy_.set(key, value);
+        state.assigned_.set(key, true);
+        handleCrossReference(state, key, value);
+      }
+      return this;
+    }
+    delete(key) {
+      if (!this.has(key)) {
+        return false;
+      }
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareMapCopy(state);
+      markChanged(state);
+      if (state.base_.has(key)) {
+        state.assigned_.set(key, false);
+      } else {
+        state.assigned_.delete(key);
+      }
+      state.copy_.delete(key);
+      return true;
+    }
+    clear() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (latest(state).size) {
+        prepareMapCopy(state);
+        markChanged(state);
+        state.assigned_ = /* @__PURE__ */ new Map();
+        each(state.base_, (key) => {
+          state.assigned_.set(key, false);
+        });
+        state.copy_.clear();
+      }
+    }
+    forEach(cb, thisArg) {
+      const state = this[DRAFT_STATE];
+      latest(state).forEach((_value, key, _map) => {
+        cb.call(thisArg, this.get(key), key, this);
+      });
+    }
+    get(key) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      const value = latest(state).get(key);
+      if (state.finalized_ || !isDraftable(value)) {
+        return value;
+      }
+      if (value !== state.base_.get(key)) {
+        return value;
+      }
+      const draft = createProxy(state.scope_, value, state, key);
+      prepareMapCopy(state);
+      state.copy_.set(key, draft);
+      return draft;
+    }
+    keys() {
+      return latest(this[DRAFT_STATE]).keys();
+    }
+    values() {
+      const iterator = this.keys();
+      return {
+        [Symbol.iterator]: () => this.values(),
+        next: () => {
+          const r = iterator.next();
+          if (r.done)
+            return r;
+          const value = this.get(r.value);
+          return {
+            done: false,
+            value
+          };
+        }
+      };
+    }
+    entries() {
+      const iterator = this.keys();
+      return {
+        [Symbol.iterator]: () => this.entries(),
+        next: () => {
+          const r = iterator.next();
+          if (r.done)
+            return r;
+          const value = this.get(r.value);
+          return {
+            done: false,
+            value: [r.value, value]
+          };
+        }
+      };
+    }
+    [(DRAFT_STATE, Symbol.iterator)]() {
+      return this.entries();
+    }
+  }
+  function proxyMap_(target, parent) {
+    const map = new DraftMap(target, parent);
+    return [map, map[DRAFT_STATE]];
+  }
+  function prepareMapCopy(state) {
+    if (!state.copy_) {
+      state.assigned_ = /* @__PURE__ */ new Map();
+      state.copy_ = new Map(state.base_);
+    }
+  }
+  class DraftSet extends Set {
+    constructor(target, parent) {
+      super();
+      this[DRAFT_STATE] = {
+        type_: 3 /* Set */,
+        parent_: parent,
+        scope_: parent ? parent.scope_ : getCurrentScope(),
+        modified_: false,
+        finalized_: false,
+        copy_: void 0,
+        base_: target,
+        draft_: this,
+        drafts_: /* @__PURE__ */ new Map(),
+        revoked_: false,
+        isManual_: false,
+        assigned_: void 0,
+        callbacks_: []
+      };
+    }
+    get size() {
+      return latest(this[DRAFT_STATE]).size;
+    }
+    has(value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!state.copy_) {
+        return state.base_.has(value);
+      }
+      if (state.copy_.has(value))
+        return true;
+      if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))
+        return true;
+      return false;
+    }
+    add(value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!this.has(value)) {
+        prepareSetCopy(state);
+        markChanged(state);
+        state.copy_.add(value);
+        handleCrossReference(state, value, value);
+      }
+      return this;
+    }
+    delete(value) {
+      if (!this.has(value)) {
+        return false;
+      }
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      markChanged(state);
+      return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (
+        /* istanbul ignore next */
+        false
+      ));
+    }
+    clear() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (latest(state).size) {
+        prepareSetCopy(state);
+        markChanged(state);
+        state.copy_.clear();
+      }
+    }
+    values() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      return state.copy_.values();
+    }
+    entries() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      return state.copy_.entries();
+    }
+    keys() {
+      return this.values();
+    }
+    [(DRAFT_STATE, Symbol.iterator)]() {
+      return this.values();
+    }
+    forEach(cb, thisArg) {
+      const iterator = this.values();
+      let result = iterator.next();
+      while (!result.done) {
+        cb.call(thisArg, result.value, result.value, this);
+        result = iterator.next();
+      }
+    }
+  }
+  function proxySet_(target, parent) {
+    const set2 = new DraftSet(target, parent);
+    return [set2, set2[DRAFT_STATE]];
+  }
+  function prepareSetCopy(state) {
+    if (!state.copy_) {
+      state.copy_ = /* @__PURE__ */ new Set();
+      state.base_.forEach((value) => {
+        if (isDraftable(value)) {
+          const draft = createProxy(state.scope_, value, state, value);
+          state.drafts_.set(value, draft);
+          state.copy_.add(draft);
+        } else {
+          state.copy_.add(value);
+        }
+      });
+    }
+  }
+  function assertUnrevoked(state) {
+    if (state.revoked_)
+      die(3, JSON.stringify(latest(state)));
+  }
+  function fixSetContents(target) {
+    if (target.type_ === 3 /* Set */ && target.copy_) {
+      const copy = new Set(target.copy_);
+      target.copy_.clear();
+      copy.forEach((value) => {
+        target.copy_.add(getValue(value));
+      });
+    }
+  }
+  loadPlugin(PluginMapSet, { proxyMap_, proxySet_, fixSetContents });
+}
+
+// src/plugins/arrayMethods.ts
+function enableArrayMethods() {
+  const SHIFTING_METHODS = /* @__PURE__ */ new Set(["shift", "unshift"]);
+  const QUEUE_METHODS = /* @__PURE__ */ new Set(["push", "pop"]);
+  const RESULT_RETURNING_METHODS = /* @__PURE__ */ new Set([
+    ...QUEUE_METHODS,
+    ...SHIFTING_METHODS
+  ]);
+  const REORDERING_METHODS = /* @__PURE__ */ new Set(["reverse", "sort"]);
+  const MUTATING_METHODS = /* @__PURE__ */ new Set([
+    ...RESULT_RETURNING_METHODS,
+    ...REORDERING_METHODS,
+    "splice"
+  ]);
+  const FIND_METHODS = /* @__PURE__ */ new Set(["find", "findLast"]);
+  const NON_MUTATING_METHODS = /* @__PURE__ */ new Set([
+    "filter",
+    "slice",
+    "concat",
+    "flat",
+    ...FIND_METHODS,
+    "findIndex",
+    "findLastIndex",
+    "some",
+    "every",
+    "indexOf",
+    "lastIndexOf",
+    "includes",
+    "join",
+    "toString",
+    "toLocaleString"
+  ]);
+  function isMutatingArrayMethod(method) {
+    return MUTATING_METHODS.has(method);
+  }
+  function isNonMutatingArrayMethod(method) {
+    return NON_MUTATING_METHODS.has(method);
+  }
+  function isArrayOperationMethod(method) {
+    return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method);
+  }
+  function enterOperation(state, method) {
+    state.operationMethod = method;
+  }
+  function exitOperation(state) {
+    state.operationMethod = void 0;
+  }
+  function executeArrayMethod(state, operation, markLength = true) {
+    prepareCopy(state);
+    const result = operation();
+    markChanged(state);
+    if (markLength)
+      state.assigned_.set("length", true);
+    return result;
+  }
+  function markAllIndicesReassigned(state) {
+    state.allIndicesReassigned_ = true;
+  }
+  function normalizeSliceIndex(index, length) {
+    if (index < 0) {
+      return Math.max(length + index, 0);
+    }
+    return Math.min(index, length);
+  }
+  function handleSimpleOperation(state, method, args) {
+    return executeArrayMethod(state, () => {
+      const result = state.copy_[method](...args);
+      if (SHIFTING_METHODS.has(method)) {
+        markAllIndicesReassigned(state);
+      }
+      return RESULT_RETURNING_METHODS.has(method) ? result : state.draft_;
+    });
+  }
+  function handleReorderingOperation(state, method, args) {
+    return executeArrayMethod(
+      state,
+      () => {
+        ;
+        state.copy_[method](...args);
+        markAllIndicesReassigned(state);
+        return state.draft_;
+      },
+      false
+    );
+  }
+  function createMethodInterceptor(state, originalMethod) {
+    return function interceptedMethod(...args) {
+      const method = originalMethod;
+      enterOperation(state, method);
+      try {
+        if (isMutatingArrayMethod(method)) {
+          if (RESULT_RETURNING_METHODS.has(method)) {
+            return handleSimpleOperation(state, method, args);
+          }
+          if (REORDERING_METHODS.has(method)) {
+            return handleReorderingOperation(state, method, args);
+          }
+          if (method === "splice") {
+            const res = executeArrayMethod(
+              state,
+              () => state.copy_.splice(...args)
+            );
+            markAllIndicesReassigned(state);
+            return res;
+          }
+        } else {
+          return handleNonMutatingOperation(state, method, args);
+        }
+      } finally {
+        exitOperation(state);
+      }
+    };
+  }
+  function handleNonMutatingOperation(state, method, args) {
+    var _a, _b;
+    const source = latest(state);
+    if (method === "filter") {
+      const predicate = args[0];
+      const result = [];
+      for (let i = 0; i < source.length; i++) {
+        if (predicate(source[i], i, source)) {
+          result.push(state.draft_[i]);
+        }
+      }
+      return result;
+    }
+    if (FIND_METHODS.has(method)) {
+      const predicate = args[0];
+      const isForward = method === "find";
+      const step = isForward ? 1 : -1;
+      const start = isForward ? 0 : source.length - 1;
+      for (let i = start; i >= 0 && i < source.length; i += step) {
+        if (predicate(source[i], i, source)) {
+          return state.draft_[i];
+        }
+      }
+      return void 0;
+    }
+    if (method === "slice") {
+      const rawStart = (_a = args[0]) != null ? _a : 0;
+      const rawEnd = (_b = args[1]) != null ? _b : source.length;
+      const start = normalizeSliceIndex(rawStart, source.length);
+      const end = normalizeSliceIndex(rawEnd, source.length);
+      const result = [];
+      for (let i = start; i < end; i++) {
+        result.push(state.draft_[i]);
+      }
+      return result;
+    }
+    return source[method](...args);
+  }
+  loadPlugin(PluginArrayMethods, {
+    createMethodInterceptor,
+    isArrayOperationMethod,
+    isMutatingArrayMethod
+  });
+}
+
+// src/immer.ts
+var immer = new Immer2();
+var produce = immer.produce;
+var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(
+  immer
+);
+var setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer);
+var setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(
+  immer
+);
+var setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(
+  immer
+);
+var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
+var createDraft = /* @__PURE__ */ immer.createDraft.bind(immer);
+var finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer);
+var castDraft = (value) => value;
+var castImmutable = (value) => value;
+export {
+  Immer2 as Immer,
+  applyPatches,
+  castDraft,
+  castImmutable,
+  createDraft,
+  current,
+  enableArrayMethods,
+  enableMapSet,
+  enablePatches,
+  finishDraft,
+  freeze,
+  DRAFTABLE as immerable,
+  isDraft,
+  isDraftable,
+  NOTHING as nothing,
+  original,
+  produce,
+  produceWithPatches,
+  setAutoFreeze,
+  setUseStrictIteration,
+  setUseStrictShallowCopy
+};
+//# sourceMappingURL=immer.legacy-esm.js.map
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.legacy-esm.js.map
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.legacy-esm.js.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../src/utils/env.ts","../src/utils/errors.ts","../src/utils/common.ts","../src/utils/plugins.ts","../src/core/scope.ts","../src/core/finalize.ts","../src/core/proxy.ts","../src/core/immerClass.ts","../src/core/current.ts","../src/plugins/patches.ts","../src/plugins/mapset.ts","../src/plugins/arrayMethods.ts","../src/immer.ts"],"sourcesContent":["// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","import {isFunction} from \"../internal\"\n\nexport const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t  ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = isFunction(e) ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nconst O = Object\n\nexport const getPrototypeOf = O.getPrototypeOf\n\nexport const CONSTRUCTOR = \"constructor\"\nexport const PROTOTYPE = \"prototype\"\n\nexport const CONFIGURABLE = \"configurable\"\nexport const ENUMERABLE = \"enumerable\"\nexport const WRITABLE = \"writable\"\nexport const VALUE = \"value\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tisArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value[CONSTRUCTOR]?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()\nconst cachedCtorStrings = new WeakMap()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || !isObjectish(value)) return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null || proto === O[PROTOTYPE]) return true\n\n\tconst Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]\n\tif (Ctor === Object) return true\n\n\tif (!isFunction(Ctor)) return false\n\n\tlet ctorString = cachedCtorStrings.get(Ctor)\n\tif (ctorString === undefined) {\n\t\tctorString = Function.toString.call(Ctor)\n\t\tcachedCtorStrings.set(Ctor, ctorString)\n\t}\n\n\treturn ctorString === objectCtorString\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n *\n * @param obj The object to iterate over\n * @param iter The iterator function\n * @param strict When true (default), includes symbols and non-enumerable properties.\n *               When false, uses looseiteration over only enumerable string properties.\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tstrict?: boolean\n): void\nexport function each(obj: any, iter: any, strict: boolean = true) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\t// If strict, we do a full iteration including symbols and non-enumerable properties\n\t\t// Otherwise, we only iterate enumerable string properties for performance\n\t\tconst keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)\n\t\tkeys.forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport let has = (\n\tthing: any,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): boolean =>\n\ttype === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: O[PROTOTYPE].hasOwnProperty.call(thing, prop)\n\n/*#__PURE__*/\nexport let get = (\n\tthing: AnyMap | AnyObject,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): any =>\n\t// @ts-ignore\n\ttype === ArchType.Map ? thing.get(prop) : thing[prop]\n\n/*#__PURE__*/\nexport let set = (\n\tthing: any,\n\tpropOrOldValue: PropertyKey,\n\tvalue: any,\n\ttype = getArchtype(thing)\n) => {\n\tif (type === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (type === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\nexport let isArray = Array.isArray\n\n/*#__PURE__*/\nexport let isMap = (target: any): target is AnyMap => target instanceof Map\n\n/*#__PURE__*/\nexport let isSet = (target: any): target is AnySet => target instanceof Set\n\nexport let isObjectish = (target: any) => typeof target === \"object\"\n\nexport let isFunction = (target: any): target is Function =>\n\ttypeof target === \"function\"\n\nexport let isBoolean = (target: any): target is boolean =>\n\ttypeof target === \"boolean\"\n\nexport function isArrayIndex(value: string | number): value is number | string {\n\tconst n = +value\n\treturn Number.isInteger(n) && String(n) === value\n}\n\nexport let getProxyDraft = <T extends any>(value: T): ImmerState | null => {\n\tif (!isObjectish(value)) return null\n\treturn (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]\n}\n\n/*#__PURE__*/\nexport let latest = (state: ImmerState): any => state.copy_ || state.base_\n\nexport let getValue = <T extends object>(value: T): T => {\n\tconst proxyDraft = getProxyDraft(value)\n\treturn proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value\n}\n\nexport let getFinalValue = (state: ImmerState): any =>\n\tstate.modified_ ? state.copy_ : state.base_\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (isArray(base)) return Array[PROTOTYPE].slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = O.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc[WRITABLE] === false) {\n\t\t\t\tdesc[WRITABLE] = true\n\t\t\t\tdesc[CONFIGURABLE] = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\t[CONFIGURABLE]: true,\n\t\t\t\t\t[WRITABLE]: true, // could live with !!desc.set as well here...\n\t\t\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t\t\t[VALUE]: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn O.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = O.create(proto)\n\t\treturn O.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tO.defineProperties(obj, {\n\t\t\tset: dontMutateMethodOverride,\n\t\t\tadd: dontMutateMethodOverride,\n\t\t\tclear: dontMutateMethodOverride,\n\t\t\tdelete: dontMutateMethodOverride\n\t\t})\n\t}\n\tO.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.values (only string-like, enumerables) instead of each()\n\t\teach(\n\t\t\tobj,\n\t\t\t(_key, value) => {\n\t\t\t\tfreeze(value, true)\n\t\t\t},\n\t\t\tfalse\n\t\t)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nconst dontMutateMethodOverride = {\n\t[VALUE]: dontMutateFrozenCollections\n}\n\nexport function isFrozen(obj: any): boolean {\n\t// Fast path: primitives and null/undefined are always \"frozen\"\n\tif (obj === null || !isObjectish(obj)) return true\n\treturn O.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie,\n\tImmerScope,\n\tProxyArrayState\n} from \"../internal\"\n\nexport const PluginMapSet = \"MapSet\"\nexport const PluginPatches = \"Patches\"\nexport const PluginArrayMethods = \"ArrayMethods\"\n\nexport type PatchesPlugin = {\n\tgeneratePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\trootScope: ImmerScope\n\t): void\n\tgenerateReplacementPatches_(\n\t\tbase: any,\n\t\treplacement: any,\n\t\trootScope: ImmerScope\n\t): void\n\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\tgetPath: (state: ImmerState) => PatchPath | null\n}\n\nexport type MapSetPlugin = {\n\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]\n\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]\n\tfixSetContents: (state: ImmerState) => void\n}\n\nexport type ArrayMethodsPlugin = {\n\tcreateMethodInterceptor: (state: ProxyArrayState, method: string) => Function\n\tisArrayOperationMethod: (method: string) => boolean\n\tisMutatingArrayMethod: (method: string) => boolean\n}\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: PatchesPlugin\n\tMapSet?: MapSetPlugin\n\tArrayMethods?: ArrayMethodsPlugin\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>\n\t!!plugins[pluginKey]\n\nexport let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {\n\tdelete plugins[pluginKey]\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin,\n\tPatchesPlugin,\n\tMapSetPlugin,\n\tisPluginLoaded,\n\tPluginMapSet,\n\tPluginPatches,\n\tArrayMethodsPlugin,\n\tPluginArrayMethods\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tpatchPlugin_?: PatchesPlugin\n\tmapSetPlugin_?: MapSetPlugin\n\tarrayMethodsPlugin_?: ArrayMethodsPlugin\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n\thandledSet_: Set<any>\n\tprocessedForPatches_: Set<any>\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport let getCurrentScope = () => currentScope!\n\nlet createScope = (\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope => ({\n\tdrafts_: [],\n\tparent_,\n\timmer_,\n\t// Whenever the modified draft contains a draft from another scope, we\n\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\tcanAutoFreeze_: true,\n\tunfinalizedDrafts_: 0,\n\thandledSet_: new Set(),\n\tprocessedForPatches_: new Set(),\n\tmapSetPlugin_: isPluginLoaded(PluginMapSet)\n\t\t? getPlugin(PluginMapSet)\n\t\t: undefined,\n\tarrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods)\n\t\t? getPlugin(PluginArrayMethods)\n\t\t: undefined\n})\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tscope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport let enterScope = (immer: Immer) =>\n\t(currentScope = createScope(currentScope, immer))\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tget,\n\tPatch,\n\tlatest,\n\tprepareCopy,\n\tgetFinalValue,\n\tgetValue,\n\tProxyArrayState\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t}\n\t\tconst {patchPlugin_} = scope\n\t\tif (patchPlugin_) {\n\t\t\tpatchPlugin_.generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft)\n\t}\n\n\tmaybeFreeze(scope, result, true)\n\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\tif (!state) {\n\t\tconst finalValue = handleValue(value, rootScope.handledSet_, rootScope)\n\t\treturn finalValue\n\t}\n\n\t// Never finalize drafts owned by another scope\n\tif (!isSameScope(state, rootScope)) {\n\t\treturn value\n\t}\n\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\treturn state.base_\n\t}\n\n\tif (!state.finalized_) {\n\t\t// Execute all registered draft finalization callbacks\n\t\tconst {callbacks_} = state\n\t\tif (callbacks_) {\n\t\t\twhile (callbacks_.length > 0) {\n\t\t\t\tconst callback = callbacks_.pop()!\n\t\t\t\tcallback(rootScope)\n\t\t\t}\n\t\t}\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t}\n\n\t// By now the root copy has been fully updated throughout its tree\n\treturn state.copy_\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n\nfunction markStateFinalized(state: ImmerState) {\n\tstate.finalized_ = true\n\tstate.scope_.unfinalizedDrafts_--\n}\n\nlet isSameScope = (state: ImmerState, rootScope: ImmerScope) =>\n\tstate.scope_ === rootScope\n\n// A reusable empty array to avoid allocations\nconst EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []\n\n// Updates all references to a draft in its parent to the finalized value.\n// This handles cases where the same draft appears multiple times in the parent, or has been moved around.\nexport function updateDraftInParent(\n\tparent: ImmerState,\n\tdraftValue: any,\n\tfinalizedValue: any,\n\toriginalKey?: string | number | symbol\n): void {\n\tconst parentCopy = latest(parent)\n\tconst parentType = parent.type_\n\n\t// Fast path: Check if draft is still at original key\n\tif (originalKey !== undefined) {\n\t\tconst currentValue = get(parentCopy, originalKey, parentType)\n\t\tif (currentValue === draftValue) {\n\t\t\t// Still at original location, just update it\n\t\t\tset(parentCopy, originalKey, finalizedValue, parentType)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Slow path: Build reverse mapping of all children\n\t// to their indices in the parent, so that we can\n\t// replace all locations where this draft appears.\n\t// We only have to build this once per parent.\n\tif (!parent.draftLocations_) {\n\t\tconst draftLocations = (parent.draftLocations_ = new Map())\n\n\t\t// Use `each` which works on Arrays, Maps, and Objects\n\t\teach(parentCopy, (key, value) => {\n\t\t\tif (isDraft(value)) {\n\t\t\t\tconst keys = draftLocations.get(value) || []\n\t\t\t\tkeys.push(key)\n\t\t\t\tdraftLocations.set(value, keys)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Look up all locations where this draft appears\n\tconst locations =\n\t\tparent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT\n\n\t// Update all locations\n\tfor (const location of locations) {\n\t\tset(parentCopy, location, finalizedValue, parentType)\n\t}\n}\n\n// Register a callback to finalize a child draft when the parent draft is finalized.\n// This assumes there is a parent -> child relationship between the two drafts,\n// and we have a key to locate the child in the parent.\nexport function registerChildFinalizationCallback(\n\tparent: ImmerState,\n\tchild: ImmerState,\n\tkey: string | number | symbol\n) {\n\tparent.callbacks_.push(function childCleanup(rootScope) {\n\t\tconst state: ImmerState = child\n\n\t\t// Can only continue if this is a draft owned by this scope\n\t\tif (!state || !isSameScope(state, rootScope)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle potential set value finalization first\n\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t// Update all locations in the parent that referenced this draft\n\t\tupdateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t})\n}\n\nfunction generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {\n\tconst shouldFinalize =\n\t\tstate.modified_ &&\n\t\t!state.finalized_ &&\n\t\t(state.type_ === ArchType.Set ||\n\t\t\t(state.type_ === ArchType.Array &&\n\t\t\t\t(state as ProxyArrayState).allIndicesReassigned_) ||\n\t\t\t(state.assigned_?.size ?? 0) > 0)\n\n\tif (shouldFinalize) {\n\t\tconst {patchPlugin_} = rootScope\n\t\tif (patchPlugin_) {\n\t\t\tconst basePath = patchPlugin_!.getPath(state)\n\n\t\t\tif (basePath) {\n\t\t\t\tpatchPlugin_!.generatePatches_(state, basePath, rootScope)\n\t\t\t}\n\t\t}\n\n\t\tmarkStateFinalized(state)\n\t}\n}\n\nexport function handleCrossReference(\n\ttarget: ImmerState,\n\tkey: string | number | symbol,\n\tvalue: any\n) {\n\tconst {scope_} = target\n\t// Check if value is a draft from this scope\n\tif (isDraft(value)) {\n\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\tif (isSameScope(state, scope_)) {\n\t\t\t// Register callback to update this location when the draft finalizes\n\n\t\t\tstate.callbacks_.push(function crossReferenceCleanup() {\n\t\t\t\t// Update the target location with finalized value\n\t\t\t\tprepareCopy(target)\n\n\t\t\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t\t\tupdateDraftInParent(target, value, finalizedValue, key)\n\t\t\t})\n\t\t}\n\t} else if (isDraftable(value)) {\n\t\t// Handle non-draft objects that might contain drafts\n\t\ttarget.callbacks_.push(function nestedDraftCleanup() {\n\t\t\tconst targetCopy = latest(target)\n\n\t\t\t// For Sets, check if value is still in the set\n\t\t\tif (target.type_ === ArchType.Set) {\n\t\t\t\tif (targetCopy.has(value)) {\n\t\t\t\t\t// Process the value to replace any nested drafts\n\t\t\t\t\thandleValue(value, scope_.handledSet_, scope_)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Maps/objects\n\t\t\t\tif (get(targetCopy, key, target.type_) === value) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tscope_.drafts_.length > 1 &&\n\t\t\t\t\t\t((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??\n\t\t\t\t\t\t\tfalse) === true &&\n\t\t\t\t\t\ttarget.copy_\n\t\t\t\t\t) {\n\t\t\t\t\t\t// This might be a non-draft value that has drafts\n\t\t\t\t\t\t// inside. We do need to recurse here to handle those.\n\t\t\t\t\t\thandleValue(\n\t\t\t\t\t\t\tget(target.copy_, key, target.type_),\n\t\t\t\t\t\t\tscope_.handledSet_,\n\t\t\t\t\t\t\tscope_\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nexport function handleValue(\n\ttarget: any,\n\thandledSet: Set<any>,\n\trootScope: ImmerScope\n) {\n\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t// This benefits especially adding large data tree's without further processing.\n\t\t// See add-data.js perf test\n\t\treturn target\n\t}\n\n\t// Skip if already handled, frozen, or not draftable\n\tif (\n\t\tisDraft(target) ||\n\t\thandledSet.has(target) ||\n\t\t!isDraftable(target) ||\n\t\tisFrozen(target)\n\t) {\n\t\treturn target\n\t}\n\n\thandledSet.add(target)\n\n\t// Process ALL properties/entries\n\teach(target, (key, value) => {\n\t\tif (isDraft(value)) {\n\t\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\t\tif (isSameScope(state, rootScope)) {\n\t\t\t\t// Replace draft with finalized value\n\n\t\t\t\tconst updatedValue = getFinalValue(state)\n\n\t\t\t\tset(target, key, updatedValue, target.type_)\n\n\t\t\t\tmarkStateFinalized(state)\n\t\t\t}\n\t\t} else if (isDraftable(value)) {\n\t\t\t// Recursively handle nested values\n\t\t\thandleValue(value, handledSet, rootScope)\n\t\t}\n\t})\n\n\treturn target\n}\n","import {\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\thandleCrossReference,\n\tWRITABLE,\n\tCONFIGURABLE,\n\tENUMERABLE,\n\tVALUE,\n\tisArray,\n\tisArrayIndex\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n\toperationMethod?: string\n\tallIndicesReassigned_?: boolean\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): [Drafted<T, ProxyState>, ProxyState] {\n\tconst baseIsArray = isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: baseIsArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\t// actually instantiated in `prepareCopy()`\n\t\tassigned_: undefined,\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false,\n\t\t// `callbacks` actually gets assigned in `createProxy`\n\t\tcallbacks_: undefined as any\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (baseIsArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn [proxy as any, state]\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tlet arrayPlugin = state.scope_.arrayMethodsPlugin_\n\t\tconst isArrayWithStringProp =\n\t\t\tstate.type_ === ArchType.Array && typeof prop === \"string\"\n\t\t// Intercept array methods so that we can override\n\t\t// behavior and skip proxy creation for perf\n\t\tif (isArrayWithStringProp) {\n\t\t\tif (arrayPlugin?.isArrayOperationMethod(prop)) {\n\t\t\t\treturn arrayPlugin.createMethodInterceptor(state, prop)\n\t\t\t}\n\t\t}\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop, state.type_)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\t// During mutating array operations, defer proxy creation for array elements\n\t\t// This optimization avoids creating unnecessary proxies during sort/reverse\n\t\tif (\n\t\t\tisArrayWithStringProp &&\n\t\t\t(state as ProxyArrayState).operationMethod &&\n\t\t\tarrayPlugin?.isMutatingArrayMethod(\n\t\t\t\t(state as ProxyArrayState).operationMethod!\n\t\t\t) &&\n\t\t\tisArrayIndex(prop)\n\t\t) {\n\t\t\t// Return raw value during mutating operations, create proxy only if modified\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\t// Ensure array keys are always numbers\n\t\t\tconst childKey = state.type_ === ArchType.Array ? +(prop as string) : prop\n\t\t\tconst childDraft = createProxy(state.scope_, value, state, childKey)\n\n\t\t\treturn (state.copy_![childKey] = childDraft)\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_!.set(prop, false)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (\n\t\t\t\tis(value, current) &&\n\t\t\t\t(value !== undefined || has(state.base_, prop, state.type_))\n\t\t\t)\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_!.set(prop, true)\n\n\t\thandleCrossReference(state, prop, value)\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\tprepareCopy(state)\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_!.set(prop, false)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tstate.assigned_!.delete(prop)\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\t[WRITABLE]: true,\n\t\t\t[CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t[VALUE]: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\n// Use `for..in` instead of `each` to work around a weird\n// prod test suite issue\nfor (let key in objectTraps) {\n\tlet fn = objectTraps[key as keyof typeof objectTraps] as Function\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\tconst args = arguments\n\t\targs[0] = args[0][0]\n\t\treturn fn.apply(this, args)\n\t}\n}\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? VALUE in desc\n\t\t\t? desc[VALUE]\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t  // prototype, we should invoke it with the draft as context!\n\t\t\t  desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: ImmerState) {\n\tif (!state.copy_) {\n\t\t// Actually create the `assigned_` map now that we\n\t\t// know this is a modified draft.\n\t\tstate.assigned_ = new Map()\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent,\n\tImmerScope,\n\tregisterChildFinalizationCallback,\n\tArchType,\n\tMapSetPlugin,\n\tAnyMap,\n\tAnySet,\n\tisObjectish,\n\tisFunction,\n\tisBoolean,\n\tPluginMapSet,\n\tPluginPatches\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\"\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\tuseStrictIteration_: boolean = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t\tuseStrictIteration?: boolean\n\t}) {\n\t\tif (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)\n\t\tif (isBoolean(config?.useStrictShallowCopy))\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t\tif (isBoolean(config?.useStrictIteration))\n\t\t\tthis.setUseStrictIteration(config!.useStrictIteration)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (isFunction(base) && !isFunction(recipe)) {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (!isFunction(recipe)) die(6)\n\t\tif (patchListener !== undefined && !isFunction(patchListener)) die(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(scope, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || !isObjectish(base)) {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n\t\t\t\t\tpatches_: p,\n\t\t\t\t\tinversePatches_: ip\n\t\t\t\t} as ImmerScope) // dummy scope\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (isFunction(base)) {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(scope, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\t/**\n\t * Pass false to use faster iteration that skips non-enumerable properties\n\t * but still handles symbols for compatibility.\n\t *\n\t * By default, strict iteration is enabled (includes all own properties).\n\t */\n\tsetUseStrictIteration(value: boolean) {\n\t\tthis.useStrictIteration_ = value\n\t}\n\n\tshouldUseStrictIteration(): boolean {\n\t\treturn this.useStrictIteration_\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(PluginPatches).applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\trootScope: ImmerScope,\n\tvalue: T,\n\tparent?: ImmerState,\n\tkey?: string | number | symbol\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\t// returning a tuple here lets us skip a proxy access\n\t// to DRAFT_STATE later\n\tconst [draft, state] = isMap(value)\n\t\t? getPlugin(PluginMapSet).proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(PluginMapSet).proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent?.scope_ ?? getCurrentScope()\n\tscope.drafts_.push(draft)\n\n\t// Ensure the parent callbacks are passed down so we actually\n\t// track all callbacks added throughout the tree\n\tstate.callbacks_ = parent?.callbacks_ ?? []\n\tstate.key_ = key\n\n\tif (parent && key !== undefined) {\n\t\tregisterChildFinalizationCallback(parent, state, key)\n\t} else {\n\t\t// It's a root draft, register it with the scope\n\t\tstate.callbacks_.push(function rootDraftCleanup(rootScope) {\n\t\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\t\tconst {patchPlugin_} = rootScope\n\n\t\t\tif (state.modified_ && patchPlugin_) {\n\t\t\t\tpatchPlugin_.generatePatches_(state, [], rootScope)\n\t\t\t}\n\t\t})\n\t}\n\n\treturn draft as any\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tlet strict = true // Default to strict for compatibility\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t\tstrict = state.scope_.immer_.shouldUseStrictIteration()\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(\n\t\tcopy,\n\t\t(key, childValue) => {\n\t\t\tset(copy, key, currentImpl(childValue))\n\t\t},\n\t\tstrict\n\t)\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors,\n\tDRAFT_STATE,\n\tgetProxyDraft,\n\tImmerScope,\n\tisObjectish,\n\tisFunction,\n\tCONSTRUCTOR,\n\tPluginPatches,\n\tisArray,\n\tPROTOTYPE\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tfunction getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {\n\t\t// Step 1: Check if state has a stored key\n\t\tif (state.key_ !== undefined) {\n\t\t\t// Step 2: Validate the key is still valid in parent\n\n\t\t\tconst parentCopy = state.parent_!.copy_ ?? state.parent_!.base_\n\t\t\tconst proxyDraft = getProxyDraft(get(parentCopy, state.key_!))\n\t\t\tconst valueAtKey = get(parentCopy, state.key_!)\n\n\t\t\tif (valueAtKey === undefined) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Check if the value at the key is still related to this draft\n\t\t\t// It should be either the draft itself, the base, or the copy\n\t\t\tif (\n\t\t\t\tvalueAtKey !== state.draft_ &&\n\t\t\t\tvalueAtKey !== state.base_ &&\n\t\t\t\tvalueAtKey !== state.copy_\n\t\t\t) {\n\t\t\t\treturn null // Value was replaced with something else\n\t\t\t}\n\t\t\tif (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n\t\t\t\treturn null // Different draft\n\t\t\t}\n\n\t\t\t// Step 3: Handle Set case specially\n\t\t\tconst isSet = state.parent_!.type_ === ArchType.Set\n\t\t\tlet key: string | number\n\n\t\t\tif (isSet) {\n\t\t\t\t// For Sets, find the index in the drafts_ map\n\t\t\t\tconst setParent = state.parent_ as SetState\n\t\t\t\tkey = Array.from(setParent.drafts_.keys()).indexOf(state.key_)\n\t\t\t} else {\n\t\t\t\tkey = state.key_ as string | number\n\t\t\t}\n\n\t\t\t// Step 4: Validate key still exists in parent\n\t\t\tif (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {\n\t\t\t\treturn null // Key deleted\n\t\t\t}\n\n\t\t\t// Step 5: Add key to path\n\t\t\tpath.push(key)\n\t\t}\n\n\t\t// Step 6: Recurse to parent if exists\n\t\tif (state.parent_) {\n\t\t\treturn getPath(state.parent_, path)\n\t\t}\n\n\t\t// Step 7: At root - reverse path and validate\n\t\tpath.reverse()\n\n\t\ttry {\n\t\t\t// Validate path can be resolved from ROOT\n\t\t\tresolvePath(state.copy_, path)\n\t\t} catch (e) {\n\t\t\treturn null // Path invalid\n\t\t}\n\n\t\treturn path\n\t}\n\n\t// NEW: Add resolvePath helper function\n\tfunction resolvePath(base: any, path: PatchPath): any {\n\t\tlet current = base\n\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\tconst key = path[i]\n\t\t\tcurrent = get(current, key)\n\t\t\tif (!isObjectish(current) || current === null) {\n\t\t\t\tthrow new Error(`Cannot resolve path at '${path.join(\"/\")}'`)\n\t\t\t}\n\t\t}\n\t\treturn current\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tscope: ImmerScope\n\t): void {\n\t\tif (state.scope_.processedForPatches_.has(state)) {\n\t\t\treturn\n\t\t}\n\n\t\tstate.scope_.processedForPatches_.add(state)\n\n\t\tconst {patches_, inversePatches_} = scope\n\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\tconst allReassigned = state.allIndicesReassigned_ === true\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tconst copiedItem = copy_[i]\n\t\t\tconst baseItem = base_[i]\n\n\t\t\tconst isAssigned = allReassigned || assigned_?.get(i.toString())\n\t\t\tif (isAssigned && copiedItem !== baseItem) {\n\t\t\t\tconst childState = copiedItem?.[DRAFT_STATE]\n\t\t\t\tif (childState && childState.modified_) {\n\t\t\t\t\t// Skip - let the child generate its own patches\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copiedItem)\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(baseItem)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_, type_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key, type_)\n\t\t\tconst value = get(copy_!, key, type_)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(\n\t\t\t\top === REMOVE\n\t\t\t\t\t? {op, path}\n\t\t\t\t\t: {op, path, value: clonePatchValueIfNeeded(value)}\n\t\t\t)\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tscope: ImmerScope\n\t): void {\n\t\tconst {patches_, inversePatches_} = scope\n\t\tpatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === CONSTRUCTOR)\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (!isObjectish(base)) die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(PluginPatches, {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_,\n\t\tgetPath\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach,\n\tgetValue,\n\tPluginMapSet,\n\thandleCrossReference\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\thandleCrossReference(state, key, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_, value, state, key)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, MapState] {\n\t\t// @ts-ignore\n\t\tconst map = new DraftMap(target, parent)\n\t\treturn [map as any, map[DRAFT_STATE]]\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t\thandleCrossReference(state, value, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, SetState] {\n\t\t// @ts-ignore\n\t\tconst set = new DraftSet(target, parent)\n\t\treturn [set as any, set[DRAFT_STATE]]\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_, value, state, value)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tfunction fixSetContents(target: ImmerState) {\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\tif (target.type_ === ArchType.Set && target.copy_) {\n\t\t\tconst copy = new Set(target.copy_)\n\t\t\ttarget.copy_.clear()\n\t\t\tcopy.forEach(value => {\n\t\t\t\ttarget.copy_!.add(getValue(value))\n\t\t\t})\n\t\t}\n\t}\n\n\tloadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})\n}\n","import {\n\tPluginArrayMethods,\n\tlatest,\n\tloadPlugin,\n\tmarkChanged,\n\tprepareCopy,\n\tProxyArrayState\n} from \"../internal\"\n\n/**\n * Methods that directly modify the array in place.\n * These operate on the copy without creating per-element proxies:\n * - `push`, `pop`: Add/remove from end\n * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)\n * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)\n * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)\n */\ntype MutatingArrayMethod =\n\t| \"push\"\n\t| \"pop\"\n\t| \"shift\"\n\t| \"unshift\"\n\t| \"splice\"\n\t| \"reverse\"\n\t| \"sort\"\n\n/**\n * Methods that read from the array without modifying it.\n * These fall into distinct categories based on return semantics:\n *\n * **Subset operations** (return drafts - mutations propagate):\n * - `filter`, `slice`: Return array of draft proxies\n * - `find`, `findLast`: Return single draft proxy or undefined\n *\n * **Transform operations** (return base values - mutations don't track):\n * - `concat`, `flat`: Create new structures, not subsets of original\n *\n * **Primitive-returning** (no draft needed):\n * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers\n * - `some`, `every`, `includes`: Return booleans\n * - `join`, `toString`, `toLocaleString`: Return strings\n */\ntype NonMutatingArrayMethod =\n\t| \"filter\"\n\t| \"slice\"\n\t| \"concat\"\n\t| \"flat\"\n\t| \"find\"\n\t| \"findIndex\"\n\t| \"findLast\"\n\t| \"findLastIndex\"\n\t| \"some\"\n\t| \"every\"\n\t| \"indexOf\"\n\t| \"lastIndexOf\"\n\t| \"includes\"\n\t| \"join\"\n\t| \"toString\"\n\t| \"toLocaleString\"\n\n/** Union of all array operation methods handled by the plugin. */\nexport type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod\n\n/**\n * Enables optimized array method handling for Immer drafts.\n *\n * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,\n * significantly improving performance for array-heavy operations.\n *\n * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):\n * Operate directly on the copy without creating per-element proxies.\n *\n * **Non-mutating methods** fall into categories:\n * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track\n * - **Transform operations** (concat, flat): Return base values - mutations don't track\n * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives\n *\n * **Important**: Callbacks for overridden methods receive base values, not drafts.\n * This is the core performance optimization.\n *\n * @example\n * ```ts\n * import { enableArrayMethods, produce } from \"immer\"\n *\n * enableArrayMethods()\n *\n * const next = produce(state, draft => {\n *   // Optimized - no proxy creation per element\n *   draft.items.sort((a, b) => a.value - b.value)\n *\n *   // filter returns drafts - mutations propagate\n *   const filtered = draft.items.filter(x => x.value > 5)\n *   filtered[0].value = 999 // Affects draft.items[originalIndex]\n * })\n * ```\n *\n * @see https://immerjs.github.io/immer/array-methods\n */\nexport function enableArrayMethods() {\n\tconst SHIFTING_METHODS = new Set<MutatingArrayMethod>([\"shift\", \"unshift\"])\n\n\tconst QUEUE_METHODS = new Set<MutatingArrayMethod>([\"push\", \"pop\"])\n\n\tconst RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...QUEUE_METHODS,\n\t\t...SHIFTING_METHODS\n\t])\n\n\tconst REORDERING_METHODS = new Set<MutatingArrayMethod>([\"reverse\", \"sort\"])\n\n\t// Optimized method detection using array-based lookup\n\tconst MUTATING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...RESULT_RETURNING_METHODS,\n\t\t...REORDERING_METHODS,\n\t\t\"splice\"\n\t])\n\n\tconst FIND_METHODS = new Set<NonMutatingArrayMethod>([\"find\", \"findLast\"])\n\n\tconst NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([\n\t\t\"filter\",\n\t\t\"slice\",\n\t\t\"concat\",\n\t\t\"flat\",\n\t\t...FIND_METHODS,\n\t\t\"findIndex\",\n\t\t\"findLastIndex\",\n\t\t\"some\",\n\t\t\"every\",\n\t\t\"indexOf\",\n\t\t\"lastIndexOf\",\n\t\t\"includes\",\n\t\t\"join\",\n\t\t\"toString\",\n\t\t\"toLocaleString\"\n\t])\n\n\t// Type guard for method detection\n\tfunction isMutatingArrayMethod(\n\t\tmethod: string\n\t): method is MutatingArrayMethod {\n\t\treturn MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isNonMutatingArrayMethod(\n\t\tmethod: string\n\t): method is NonMutatingArrayMethod {\n\t\treturn NON_MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isArrayOperationMethod(\n\t\tmethod: string\n\t): method is ArrayOperationMethod {\n\t\treturn isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)\n\t}\n\n\tfunction enterOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: ArrayOperationMethod\n\t) {\n\t\tstate.operationMethod = method\n\t}\n\n\tfunction exitOperation(state: ProxyArrayState) {\n\t\tstate.operationMethod = undefined\n\t}\n\n\t// Shared utility functions for array method handlers\n\tfunction executeArrayMethod<T>(\n\t\tstate: ProxyArrayState,\n\t\toperation: () => T,\n\t\tmarkLength = true\n\t): T {\n\t\tprepareCopy(state)\n\t\tconst result = operation()\n\t\tmarkChanged(state)\n\t\tif (markLength) state.assigned_!.set(\"length\", true)\n\t\treturn result\n\t}\n\n\tfunction markAllIndicesReassigned(state: ProxyArrayState) {\n\t\tstate.allIndicesReassigned_ = true\n\t}\n\n\tfunction normalizeSliceIndex(index: number, length: number): number {\n\t\tif (index < 0) {\n\t\t\treturn Math.max(length + index, 0)\n\t\t}\n\t\treturn Math.min(index, length)\n\t}\n\n\t/**\n\t * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).\n\t *\n\t * Operates directly on `state.copy_` without creating per-element proxies.\n\t * For shifting methods (shift, unshift), marks all indices as reassigned since\n\t * indices shift.\n\t *\n\t * @returns For push/pop/shift/unshift: the native method result. For others: the draft.\n\t */\n\tfunction handleSimpleOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(state, () => {\n\t\t\tconst result = (state.copy_! as any)[method](...args)\n\n\t\t\t// Handle index reassignment for shifting methods\n\t\t\tif (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t}\n\n\t\t\t// Return appropriate value based on method\n\t\t\treturn RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)\n\t\t\t\t? result\n\t\t\t\t: state.draft_\n\t\t})\n\t}\n\n\t/**\n\t * Handles reordering operations (reverse, sort) that change element order.\n\t *\n\t * Operates directly on `state.copy_` and marks all indices as reassigned\n\t * since element positions change. Does not mark length as changed since\n\t * these operations preserve array length.\n\t *\n\t * @returns The draft proxy for method chaining.\n\t */\n\tfunction handleReorderingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(\n\t\t\tstate,\n\t\t\t() => {\n\t\t\t\t;(state.copy_! as any)[method](...args)\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\treturn state.draft_\n\t\t\t},\n\t\t\tfalse\n\t\t) // Don't mark length as changed\n\t}\n\n\t/**\n\t * Creates an interceptor function for a specific array method.\n\t *\n\t * The interceptor wraps array method calls to:\n\t * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap\n\t *    to detect we're inside an optimized method and skip proxy creation)\n\t * 2. Route to appropriate handler based on method type\n\t * 3. Clean up the operation flag in `finally` block\n\t *\n\t * The `operationMethod` flag is the key mechanism that enables the proxy's `get`\n\t * trap to return base values instead of creating nested proxies during iteration.\n\t *\n\t * @param state - The proxy array state\n\t * @param originalMethod - Name of the array method being intercepted\n\t * @returns Interceptor function that handles the method call\n\t */\n\tfunction createMethodInterceptor(\n\t\tstate: ProxyArrayState,\n\t\toriginalMethod: string\n\t) {\n\t\treturn function interceptedMethod(...args: any[]) {\n\t\t\t// Enter operation mode - this flag tells the proxy's get trap to return\n\t\t\t// base values instead of creating nested proxies during iteration\n\t\t\tconst method = originalMethod as ArrayOperationMethod\n\t\t\tenterOperation(state, method)\n\n\t\t\ttry {\n\t\t\t\t// Check if this is a mutating method\n\t\t\t\tif (isMutatingArrayMethod(method)) {\n\t\t\t\t\t// Direct method dispatch - no configuration lookup needed\n\t\t\t\t\tif (RESULT_RETURNING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleSimpleOperation(state, method, args)\n\t\t\t\t\t}\n\t\t\t\t\tif (REORDERING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleReorderingOperation(state, method, args)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === \"splice\") {\n\t\t\t\t\t\tconst res = executeArrayMethod(state, () =>\n\t\t\t\t\t\t\tstate.copy_!.splice(...(args as [number, number, ...any[]]))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\t\t\treturn res\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle non-mutating methods\n\t\t\t\t\treturn handleNonMutatingOperation(state, method, args)\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// Always exit operation mode - must be in finally to handle exceptions\n\t\t\t\texitOperation(state)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Handles non-mutating array methods with different return semantics.\n\t *\n\t * **Subset operations** return draft proxies for mutation tracking:\n\t * - `filter`, `slice`: Return `state.draft_[i]` for each selected element\n\t * - `find`, `findLast`: Return `state.draft_[i]` for the found element\n\t *\n\t * This allows mutations on returned elements to propagate back to the draft:\n\t * ```ts\n\t * const filtered = draft.items.filter(x => x.value > 5)\n\t * filtered[0].value = 999 // Mutates draft.items[originalIndex]\n\t * ```\n\t *\n\t * **Transform operations** return base values (no draft tracking):\n\t * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.\n\t *   Since the result structure differs from the original, tracking mutations\n\t *   back to specific draft indices would be impractical/impossible.\n\t *\n\t * **Primitive operations** return the native result directly:\n\t * - `indexOf`, `includes`, `some`, `every`, `join`, etc.\n\t *\n\t * @param state - The proxy array state\n\t * @param method - The non-mutating method name\n\t * @param args - Arguments passed to the method\n\t * @returns Drafts for subset operations, base values for transforms, primitives otherwise\n\t */\n\tfunction handleNonMutatingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: NonMutatingArrayMethod,\n\t\targs: any[]\n\t) {\n\t\tconst source = latest(state)\n\n\t\t// Methods that return arrays with selected items - need to return drafts\n\t\tif (method === \"filter\") {\n\t\t\tconst predicate = args[0]\n\t\t\tconst result: any[] = []\n\n\t\t\t// First pass: call predicate on base values to determine which items pass\n\t\t\tfor (let i = 0; i < source.length; i++) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\t// Only create draft for items that passed the predicate\n\t\t\t\t\tresult.push(state.draft_[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\tif (FIND_METHODS.has(method)) {\n\t\t\tconst predicate = args[0]\n\t\t\tconst isForward = method === \"find\"\n\t\t\tconst step = isForward ? 1 : -1\n\t\t\tconst start = isForward ? 0 : source.length - 1\n\n\t\t\tfor (let i = start; i >= 0 && i < source.length; i += step) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\treturn state.draft_[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (method === \"slice\") {\n\t\t\tconst rawStart = args[0] ?? 0\n\t\t\tconst rawEnd = args[1] ?? source.length\n\n\t\t\t// Normalize negative indices\n\t\t\tconst start = normalizeSliceIndex(rawStart, source.length)\n\t\t\tconst end = normalizeSliceIndex(rawEnd, source.length)\n\n\t\t\tconst result: any[] = []\n\n\t\t\t// Return drafts for items in the slice range\n\t\t\tfor (let i = start; i < end; i++) {\n\t\t\t\tresult.push(state.draft_[i])\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\t// For other methods, call on base array directly:\n\t\t// - indexOf, includes, join, toString: Return primitives, no draft needed\n\t\t// - concat, flat: Return NEW arrays (not subsets). Elements are base values.\n\t\t//   This is intentional - concat/flat create new data structures rather than\n\t\t//   selecting subsets of the original, making draft tracking impractical.\n\t\treturn source[method as keyof typeof Array.prototype](...args)\n\t}\n\n\tloadPlugin(PluginArrayMethods, {\n\t\tcreateMethodInterceptor,\n\t\tisArrayOperationMethod,\n\t\tisMutatingArrayMethod\n\t})\n}\n","import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = /* @__PURE__ */ immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(\n\timmer\n)\n\n/**\n * Pass false to use loose iteration that only processes enumerable string properties.\n * This skips symbols and non-enumerable properties for maximum performance.\n *\n * By default, strict iteration is enabled (includes all own properties).\n */\nexport const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(\n\timmer\n)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = /* @__PURE__ */ immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport let castDraft = <T>(value: T): Draft<T> => value as any\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport let castImmutable = <T>(value: T): Immutable<T> => value as any\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableArrayMethods} from \"./plugins/arrayMethods\"\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKO,IAAM,UAAyB,OAAO,IAAI,eAAe;AAUzD,IAAM,YAA2B,OAAO,IAAI,iBAAiB;AAE7D,IAAM,cAA6B,OAAO,IAAI,aAAa;;;ACf3D,IAAM,SACZ,QAAQ,IAAI,aAAa,eACtB;AAAA;AAAA,EAEA,SAAS,QAAgB;AACxB,WAAO,mBAAmB,yFAAyF;AAAA,EACpH;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,sJAAsJ;AAAA,EAC9J;AAAA,EACA;AAAA,EACA,SAAS,MAAW;AACnB,WACC,yHACA;AAAA,EAEF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,mCAAmC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,oCAAoC;AAAA,EAC5C;AAAA;AAAA;AAGA,IACA,CAAC;AAEE,SAAS,IAAI,UAAkB,MAAoB;AACzD,MAAI,QAAQ,IAAI,aAAa,cAAc;AAC1C,UAAM,IAAI,OAAO,KAAK;AACtB,UAAM,MAAM,WAAW,CAAC,IAAI,EAAE,MAAM,MAAM,IAAW,IAAI;AACzD,UAAM,IAAI,MAAM,WAAW,KAAK;AAAA,EACjC;AACA,QAAM,IAAI;AAAA,IACT,8BAA8B;AAAA,EAC/B;AACD;;;ACnCA,IAAM,IAAI;AAEH,IAAM,iBAAiB,EAAE;AAEzB,IAAM,cAAc;AACpB,IAAM,YAA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immer/dist/immer.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1644 @@
+// src/utils/env.ts
+var NOTHING = Symbol.for("immer-nothing");
+var DRAFTABLE = Symbol.for("immer-draftable");
+var DRAFT_STATE = Symbol.for("immer-state");
+
+// src/utils/errors.ts
+var errors = process.env.NODE_ENV !== "production" ? [
+  // All error codes, starting by 0:
+  function(plugin) {
+    return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
+  },
+  function(thing) {
+    return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
+  },
+  "This object has been frozen and should not be mutated",
+  function(data) {
+    return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
+  },
+  "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
+  "Immer forbids circular references",
+  "The first or second argument to `produce` must be a function",
+  "The third argument to `produce` must be a function or undefined",
+  "First argument to `createDraft` must be a plain object, an array, or an immerable object",
+  "First argument to `finishDraft` must be a draft returned by `createDraft`",
+  function(thing) {
+    return `'current' expects a draft, got: ${thing}`;
+  },
+  "Object.defineProperty() cannot be used on an Immer draft",
+  "Object.setPrototypeOf() cannot be used on an Immer draft",
+  "Immer only supports deleting array indices",
+  "Immer only supports setting array indices and the 'length' property",
+  function(thing) {
+    return `'original' expects a draft, got: ${thing}`;
+  }
+  // Note: if more errors are added, the errorOffset in Patches.ts should be increased
+  // See Patches.ts for additional errors
+] : [];
+function die(error, ...args) {
+  if (process.env.NODE_ENV !== "production") {
+    const e = errors[error];
+    const msg = isFunction(e) ? e.apply(null, args) : e;
+    throw new Error(`[Immer] ${msg}`);
+  }
+  throw new Error(
+    `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
+  );
+}
+
+// src/utils/common.ts
+var O = Object;
+var getPrototypeOf = O.getPrototypeOf;
+var CONSTRUCTOR = "constructor";
+var PROTOTYPE = "prototype";
+var CONFIGURABLE = "configurable";
+var ENUMERABLE = "enumerable";
+var WRITABLE = "writable";
+var VALUE = "value";
+var isDraft = (value) => !!value && !!value[DRAFT_STATE];
+function isDraftable(value) {
+  if (!value)
+    return false;
+  return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
+}
+var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
+var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
+function isPlainObject(value) {
+  if (!value || !isObjectish(value))
+    return false;
+  const proto = getPrototypeOf(value);
+  if (proto === null || proto === O[PROTOTYPE])
+    return true;
+  const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
+  if (Ctor === Object)
+    return true;
+  if (!isFunction(Ctor))
+    return false;
+  let ctorString = cachedCtorStrings.get(Ctor);
+  if (ctorString === void 0) {
+    ctorString = Function.toString.call(Ctor);
+    cachedCtorStrings.set(Ctor, ctorString);
+  }
+  return ctorString === objectCtorString;
+}
+function original(value) {
+  if (!isDraft(value))
+    die(15, value);
+  return value[DRAFT_STATE].base_;
+}
+function each(obj, iter, strict = true) {
+  if (getArchtype(obj) === 0 /* Object */) {
+    const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
+    keys.forEach((key) => {
+      iter(key, obj[key], obj);
+    });
+  } else {
+    obj.forEach((entry, index) => iter(index, entry, obj));
+  }
+}
+function getArchtype(thing) {
+  const state = thing[DRAFT_STATE];
+  return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
+}
+var has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
+var get = (thing, prop, type = getArchtype(thing)) => (
+  // @ts-ignore
+  type === 2 /* Map */ ? thing.get(prop) : thing[prop]
+);
+var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
+  if (type === 2 /* Map */)
+    thing.set(propOrOldValue, value);
+  else if (type === 3 /* Set */) {
+    thing.add(value);
+  } else
+    thing[propOrOldValue] = value;
+};
+function is(x, y) {
+  if (x === y) {
+    return x !== 0 || 1 / x === 1 / y;
+  } else {
+    return x !== x && y !== y;
+  }
+}
+var isArray = Array.isArray;
+var isMap = (target) => target instanceof Map;
+var isSet = (target) => target instanceof Set;
+var isObjectish = (target) => typeof target === "object";
+var isFunction = (target) => typeof target === "function";
+var isBoolean = (target) => typeof target === "boolean";
+function isArrayIndex(value) {
+  const n = +value;
+  return Number.isInteger(n) && String(n) === value;
+}
+var getProxyDraft = (value) => {
+  if (!isObjectish(value))
+    return null;
+  return value?.[DRAFT_STATE];
+};
+var latest = (state) => state.copy_ || state.base_;
+var getValue = (value) => {
+  const proxyDraft = getProxyDraft(value);
+  return proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value;
+};
+var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
+function shallowCopy(base, strict) {
+  if (isMap(base)) {
+    return new Map(base);
+  }
+  if (isSet(base)) {
+    return new Set(base);
+  }
+  if (isArray(base))
+    return Array[PROTOTYPE].slice.call(base);
+  const isPlain = isPlainObject(base);
+  if (strict === true || strict === "class_only" && !isPlain) {
+    const descriptors = O.getOwnPropertyDescriptors(base);
+    delete descriptors[DRAFT_STATE];
+    let keys = Reflect.ownKeys(descriptors);
+    for (let i = 0; i < keys.length; i++) {
+      const key = keys[i];
+      const desc = descriptors[key];
+      if (desc[WRITABLE] === false) {
+        desc[WRITABLE] = true;
+        desc[CONFIGURABLE] = true;
+      }
+      if (desc.get || desc.set)
+        descriptors[key] = {
+          [CONFIGURABLE]: true,
+          [WRITABLE]: true,
+          // could live with !!desc.set as well here...
+          [ENUMERABLE]: desc[ENUMERABLE],
+          [VALUE]: base[key]
+        };
+    }
+    return O.create(getPrototypeOf(base), descriptors);
+  } else {
+    const proto = getPrototypeOf(base);
+    if (proto !== null && isPlain) {
+      return { ...base };
+    }
+    const obj = O.create(proto);
+    return O.assign(obj, base);
+  }
+}
+function freeze(obj, deep = false) {
+  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
+    return obj;
+  if (getArchtype(obj) > 1) {
+    O.defineProperties(obj, {
+      set: dontMutateMethodOverride,
+      add: dontMutateMethodOverride,
+      clear: dontMutateMethodOverride,
+      delete: dontMutateMethodOverride
+    });
+  }
+  O.freeze(obj);
+  if (deep)
+    each(
+      obj,
+      (_key, value) => {
+        freeze(value, true);
+      },
+      false
+    );
+  return obj;
+}
+function dontMutateFrozenCollections() {
+  die(2);
+}
+var dontMutateMethodOverride = {
+  [VALUE]: dontMutateFrozenCollections
+};
+function isFrozen(obj) {
+  if (obj === null || !isObjectish(obj))
+    return true;
+  return O.isFrozen(obj);
+}
+
+// src/utils/plugins.ts
+var PluginMapSet = "MapSet";
+var PluginPatches = "Patches";
+var PluginArrayMethods = "ArrayMethods";
+var plugins = {};
+function getPlugin(pluginKey) {
+  const plugin = plugins[pluginKey];
+  if (!plugin) {
+    die(0, pluginKey);
+  }
+  return plugin;
+}
+var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
+function loadPlugin(pluginKey, implementation) {
+  if (!plugins[pluginKey])
+    plugins[pluginKey] = implementation;
+}
+
+// src/core/scope.ts
+var currentScope;
+var getCurrentScope = () => currentScope;
+var createScope = (parent_, immer_) => ({
+  drafts_: [],
+  parent_,
+  immer_,
+  // Whenever the modified draft contains a draft from another scope, we
+  // need to prevent auto-freezing so the unowned draft can be finalized.
+  canAutoFreeze_: true,
+  unfinalizedDrafts_: 0,
+  handledSet_: /* @__PURE__ */ new Set(),
+  processedForPatches_: /* @__PURE__ */ new Set(),
+  mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
+  arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
+});
+function usePatchesInScope(scope, patchListener) {
+  if (patchListener) {
+    scope.patchPlugin_ = getPlugin(PluginPatches);
+    scope.patches_ = [];
+    scope.inversePatches_ = [];
+    scope.patchListener_ = patchListener;
+  }
+}
+function revokeScope(scope) {
+  leaveScope(scope);
+  scope.drafts_.forEach(revokeDraft);
+  scope.drafts_ = null;
+}
+function leaveScope(scope) {
+  if (scope === currentScope) {
+    currentScope = scope.parent_;
+  }
+}
+var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
+function revokeDraft(draft) {
+  const state = draft[DRAFT_STATE];
+  if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
+    state.revoke_();
+  else
+    state.revoked_ = true;
+}
+
+// src/core/finalize.ts
+function processResult(result, scope) {
+  scope.unfinalizedDrafts_ = scope.drafts_.length;
+  const baseDraft = scope.drafts_[0];
+  const isReplaced = result !== void 0 && result !== baseDraft;
+  if (isReplaced) {
+    if (baseDraft[DRAFT_STATE].modified_) {
+      revokeScope(scope);
+      die(4);
+    }
+    if (isDraftable(result)) {
+      result = finalize(scope, result);
+    }
+    const { patchPlugin_ } = scope;
+    if (patchPlugin_) {
+      patchPlugin_.generateReplacementPatches_(
+        baseDraft[DRAFT_STATE].base_,
+        result,
+        scope
+      );
+    }
+  } else {
+    result = finalize(scope, baseDraft);
+  }
+  maybeFreeze(scope, result, true);
+  revokeScope(scope);
+  if (scope.patches_) {
+    scope.patchListener_(scope.patches_, scope.inversePatches_);
+  }
+  return result !== NOTHING ? result : void 0;
+}
+function finalize(rootScope, value) {
+  if (isFrozen(value))
+    return value;
+  const state = value[DRAFT_STATE];
+  if (!state) {
+    const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
+    return finalValue;
+  }
+  if (!isSameScope(state, rootScope)) {
+    return value;
+  }
+  if (!state.modified_) {
+    return state.base_;
+  }
+  if (!state.finalized_) {
+    const { callbacks_ } = state;
+    if (callbacks_) {
+      while (callbacks_.length > 0) {
+        const callback = callbacks_.pop();
+        callback(rootScope);
+      }
+    }
+    generatePatchesAndFinalize(state, rootScope);
+  }
+  return state.copy_;
+}
+function maybeFreeze(scope, value, deep = false) {
+  if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
+    freeze(value, deep);
+  }
+}
+function markStateFinalized(state) {
+  state.finalized_ = true;
+  state.scope_.unfinalizedDrafts_--;
+}
+var isSameScope = (state, rootScope) => state.scope_ === rootScope;
+var EMPTY_LOCATIONS_RESULT = [];
+function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
+  const parentCopy = latest(parent);
+  const parentType = parent.type_;
+  if (originalKey !== void 0) {
+    const currentValue = get(parentCopy, originalKey, parentType);
+    if (currentValue === draftValue) {
+      set(parentCopy, originalKey, finalizedValue, parentType);
+      return;
+    }
+  }
+  if (!parent.draftLocations_) {
+    const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
+    each(parentCopy, (key, value) => {
+      if (isDraft(value)) {
+        const keys = draftLocations.get(value) || [];
+        keys.push(key);
+        draftLocations.set(value, keys);
+      }
+    });
+  }
+  const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
+  for (const location of locations) {
+    set(parentCopy, location, finalizedValue, parentType);
+  }
+}
+function registerChildFinalizationCallback(parent, child, key) {
+  parent.callbacks_.push(function childCleanup(rootScope) {
+    const state = child;
+    if (!state || !isSameScope(state, rootScope)) {
+      return;
+    }
+    rootScope.mapSetPlugin_?.fixSetContents(state);
+    const finalizedValue = getFinalValue(state);
+    updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
+    generatePatchesAndFinalize(state, rootScope);
+  });
+}
+function generatePatchesAndFinalize(state, rootScope) {
+  const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);
+  if (shouldFinalize) {
+    const { patchPlugin_ } = rootScope;
+    if (patchPlugin_) {
+      const basePath = patchPlugin_.getPath(state);
+      if (basePath) {
+        patchPlugin_.generatePatches_(state, basePath, rootScope);
+      }
+    }
+    markStateFinalized(state);
+  }
+}
+function handleCrossReference(target, key, value) {
+  const { scope_ } = target;
+  if (isDraft(value)) {
+    const state = value[DRAFT_STATE];
+    if (isSameScope(state, scope_)) {
+      state.callbacks_.push(function crossReferenceCleanup() {
+        prepareCopy(target);
+        const finalizedValue = getFinalValue(state);
+        updateDraftInParent(target, value, finalizedValue, key);
+      });
+    }
+  } else if (isDraftable(value)) {
+    target.callbacks_.push(function nestedDraftCleanup() {
+      const targetCopy = latest(target);
+      if (target.type_ === 3 /* Set */) {
+        if (targetCopy.has(value)) {
+          handleValue(value, scope_.handledSet_, scope_);
+        }
+      } else {
+        if (get(targetCopy, key, target.type_) === value) {
+          if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {
+            handleValue(
+              get(target.copy_, key, target.type_),
+              scope_.handledSet_,
+              scope_
+            );
+          }
+        }
+      }
+    });
+  }
+}
+function handleValue(target, handledSet, rootScope) {
+  if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
+    return target;
+  }
+  if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
+    return target;
+  }
+  handledSet.add(target);
+  each(target, (key, value) => {
+    if (isDraft(value)) {
+      const state = value[DRAFT_STATE];
+      if (isSameScope(state, rootScope)) {
+        const updatedValue = getFinalValue(state);
+        set(target, key, updatedValue, target.type_);
+        markStateFinalized(state);
+      }
+    } else if (isDraftable(value)) {
+      handleValue(value, handledSet, rootScope);
+    }
+  });
+  return target;
+}
+
+// src/core/proxy.ts
+function createProxyProxy(base, parent) {
+  const baseIsArray = isArray(base);
+  const state = {
+    type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,
+    // Track which produce call this is associated with.
+    scope_: parent ? parent.scope_ : getCurrentScope(),
+    // True for both shallow and deep changes.
+    modified_: false,
+    // Used during finalization.
+    finalized_: false,
+    // Track which properties have been assigned (true) or deleted (false).
+    // actually instantiated in `prepareCopy()`
+    assigned_: void 0,
+    // The parent draft state.
+    parent_: parent,
+    // The base state.
+    base_: base,
+    // The base proxy.
+    draft_: null,
+    // set below
+    // The base copy with any updated values.
+    copy_: null,
+    // Called by the `produce` function.
+    revoke_: null,
+    isManual_: false,
+    // `callbacks` actually gets assigned in `createProxy`
+    callbacks_: void 0
+  };
+  let target = state;
+  let traps = objectTraps;
+  if (baseIsArray) {
+    target = [state];
+    traps = arrayTraps;
+  }
+  const { revoke, proxy } = Proxy.revocable(target, traps);
+  state.draft_ = proxy;
+  state.revoke_ = revoke;
+  return [proxy, state];
+}
+var objectTraps = {
+  get(state, prop) {
+    if (prop === DRAFT_STATE)
+      return state;
+    let arrayPlugin = state.scope_.arrayMethodsPlugin_;
+    const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === "string";
+    if (isArrayWithStringProp) {
+      if (arrayPlugin?.isArrayOperationMethod(prop)) {
+        return arrayPlugin.createMethodInterceptor(state, prop);
+      }
+    }
+    const source = latest(state);
+    if (!has(source, prop, state.type_)) {
+      return readPropFromProto(state, source, prop);
+    }
+    const value = source[prop];
+    if (state.finalized_ || !isDraftable(value)) {
+      return value;
+    }
+    if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(
+      state.operationMethod
+    ) && isArrayIndex(prop)) {
+      return value;
+    }
+    if (value === peek(state.base_, prop)) {
+      prepareCopy(state);
+      const childKey = state.type_ === 1 /* Array */ ? +prop : prop;
+      const childDraft = createProxy(state.scope_, value, state, childKey);
+      return state.copy_[childKey] = childDraft;
+    }
+    return value;
+  },
+  has(state, prop) {
+    return prop in latest(state);
+  },
+  ownKeys(state) {
+    return Reflect.ownKeys(latest(state));
+  },
+  set(state, prop, value) {
+    const desc = getDescriptorFromProto(latest(state), prop);
+    if (desc?.set) {
+      desc.set.call(state.draft_, value);
+      return true;
+    }
+    if (!state.modified_) {
+      const current2 = peek(latest(state), prop);
+      const currentState = current2?.[DRAFT_STATE];
+      if (currentState && currentState.base_ === value) {
+        state.copy_[prop] = value;
+        state.assigned_.set(prop, false);
+        return true;
+      }
+      if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))
+        return true;
+      prepareCopy(state);
+      markChanged(state);
+    }
+    if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
+    (value !== void 0 || prop in state.copy_) || // special case: NaN
+    Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
+      return true;
+    state.copy_[prop] = value;
+    state.assigned_.set(prop, true);
+    handleCrossReference(state, prop, value);
+    return true;
+  },
+  deleteProperty(state, prop) {
+    prepareCopy(state);
+    if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
+      state.assigned_.set(prop, false);
+      markChanged(state);
+    } else {
+      state.assigned_.delete(prop);
+    }
+    if (state.copy_) {
+      delete state.copy_[prop];
+    }
+    return true;
+  },
+  // Note: We never coerce `desc.value` into an Immer draft, because we can't make
+  // the same guarantee in ES5 mode.
+  getOwnPropertyDescriptor(state, prop) {
+    const owner = latest(state);
+    const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
+    if (!desc)
+      return desc;
+    return {
+      [WRITABLE]: true,
+      [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== "length",
+      [ENUMERABLE]: desc[ENUMERABLE],
+      [VALUE]: owner[prop]
+    };
+  },
+  defineProperty() {
+    die(11);
+  },
+  getPrototypeOf(state) {
+    return getPrototypeOf(state.base_);
+  },
+  setPrototypeOf() {
+    die(12);
+  }
+};
+var arrayTraps = {};
+for (let key in objectTraps) {
+  let fn = objectTraps[key];
+  arrayTraps[key] = function() {
+    const args = arguments;
+    args[0] = args[0][0];
+    return fn.apply(this, args);
+  };
+}
+arrayTraps.deleteProperty = function(state, prop) {
+  if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
+    die(13);
+  return arrayTraps.set.call(this, state, prop, void 0);
+};
+arrayTraps.set = function(state, prop, value) {
+  if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
+    die(14);
+  return objectTraps.set.call(this, state[0], prop, value, state[0]);
+};
+function peek(draft, prop) {
+  const state = draft[DRAFT_STATE];
+  const source = state ? latest(state) : draft;
+  return source[prop];
+}
+function readPropFromProto(state, source, prop) {
+  const desc = getDescriptorFromProto(source, prop);
+  return desc ? VALUE in desc ? desc[VALUE] : (
+    // This is a very special case, if the prop is a getter defined by the
+    // prototype, we should invoke it with the draft as context!
+    desc.get?.call(state.draft_)
+  ) : void 0;
+}
+function getDescriptorFromProto(source, prop) {
+  if (!(prop in source))
+    return void 0;
+  let proto = getPrototypeOf(source);
+  while (proto) {
+    const desc = Object.getOwnPropertyDescriptor(proto, prop);
+    if (desc)
+      return desc;
+    proto = getPrototypeOf(proto);
+  }
+  return void 0;
+}
+function markChanged(state) {
+  if (!state.modified_) {
+    state.modified_ = true;
+    if (state.parent_) {
+      markChanged(state.parent_);
+    }
+  }
+}
+function prepareCopy(state) {
+  if (!state.copy_) {
+    state.assigned_ = /* @__PURE__ */ new Map();
+    state.copy_ = shallowCopy(
+      state.base_,
+      state.scope_.immer_.useStrictShallowCopy_
+    );
+  }
+}
+
+// src/core/immerClass.ts
+var Immer2 = class {
+  constructor(config) {
+    this.autoFreeze_ = true;
+    this.useStrictShallowCopy_ = false;
+    this.useStrictIteration_ = false;
+    /**
+     * The `produce` function takes a value and a "recipe function" (whose
+     * return value often depends on the base state). The recipe function is
+     * free to mutate its first argument however it wants. All mutations are
+     * only ever applied to a __copy__ of the base state.
+     *
+     * Pass only a function to create a "curried producer" which relieves you
+     * from passing the recipe function every time.
+     *
+     * Only plain objects and arrays are made mutable. All other objects are
+     * considered uncopyable.
+     *
+     * Note: This function is __bound__ to its `Immer` instance.
+     *
+     * @param {any} base - the initial state
+     * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
+     * @param {Function} patchListener - optional function that will be called with all the patches produced here
+     * @returns {any} a new state, or the initial state if nothing was modified
+     */
+    this.produce = (base, recipe, patchListener) => {
+      if (isFunction(base) && !isFunction(recipe)) {
+        const defaultBase = recipe;
+        recipe = base;
+        const self = this;
+        return function curriedProduce(base2 = defaultBase, ...args) {
+          return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
+        };
+      }
+      if (!isFunction(recipe))
+        die(6);
+      if (patchListener !== void 0 && !isFunction(patchListener))
+        die(7);
+      let result;
+      if (isDraftable(base)) {
+        const scope = enterScope(this);
+        const proxy = createProxy(scope, base, void 0);
+        let hasError = true;
+        try {
+          result = recipe(proxy);
+          hasError = false;
+        } finally {
+          if (hasError)
+            revokeScope(scope);
+          else
+            leaveScope(scope);
+        }
+        usePatchesInScope(scope, patchListener);
+        return processResult(result, scope);
+      } else if (!base || !isObjectish(base)) {
+        result = recipe(base);
+        if (result === void 0)
+          result = base;
+        if (result === NOTHING)
+          result = void 0;
+        if (this.autoFreeze_)
+          freeze(result, true);
+        if (patchListener) {
+          const p = [];
+          const ip = [];
+          getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
+            patches_: p,
+            inversePatches_: ip
+          });
+          patchListener(p, ip);
+        }
+        return result;
+      } else
+        die(1, base);
+    };
+    this.produceWithPatches = (base, recipe) => {
+      if (isFunction(base)) {
+        return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
+      }
+      let patches, inversePatches;
+      const result = this.produce(base, recipe, (p, ip) => {
+        patches = p;
+        inversePatches = ip;
+      });
+      return [result, patches, inversePatches];
+    };
+    if (isBoolean(config?.autoFreeze))
+      this.setAutoFreeze(config.autoFreeze);
+    if (isBoolean(config?.useStrictShallowCopy))
+      this.setUseStrictShallowCopy(config.useStrictShallowCopy);
+    if (isBoolean(config?.useStrictIteration))
+      this.setUseStrictIteration(config.useStrictIteration);
+  }
+  createDraft(base) {
+    if (!isDraftable(base))
+      die(8);
+    if (isDraft(base))
+      base = current(base);
+    const scope = enterScope(this);
+    const proxy = createProxy(scope, base, void 0);
+    proxy[DRAFT_STATE].isManual_ = true;
+    leaveScope(scope);
+    return proxy;
+  }
+  finishDraft(draft, patchListener) {
+    const state = draft && draft[DRAFT_STATE];
+    if (!state || !state.isManual_)
+      die(9);
+    const { scope_: scope } = state;
+    usePatchesInScope(scope, patchListener);
+    return processResult(void 0, scope);
+  }
+  /**
+   * Pass true to automatically freeze all copies created by Immer.
+   *
+   * By default, auto-freezing is enabled.
+   */
+  setAutoFreeze(value) {
+    this.autoFreeze_ = value;
+  }
+  /**
+   * Pass true to enable strict shallow copy.
+   *
+   * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+   */
+  setUseStrictShallowCopy(value) {
+    this.useStrictShallowCopy_ = value;
+  }
+  /**
+   * Pass false to use faster iteration that skips non-enumerable properties
+   * but still handles symbols for compatibility.
+   *
+   * By default, strict iteration is enabled (includes all own properties).
+   */
+  setUseStrictIteration(value) {
+    this.useStrictIteration_ = value;
+  }
+  shouldUseStrictIteration() {
+    return this.useStrictIteration_;
+  }
+  applyPatches(base, patches) {
+    let i;
+    for (i = patches.length - 1; i >= 0; i--) {
+      const patch = patches[i];
+      if (patch.path.length === 0 && patch.op === "replace") {
+        base = patch.value;
+        break;
+      }
+    }
+    if (i > -1) {
+      patches = patches.slice(i + 1);
+    }
+    const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
+    if (isDraft(base)) {
+      return applyPatchesImpl(base, patches);
+    }
+    return this.produce(
+      base,
+      (draft) => applyPatchesImpl(draft, patches)
+    );
+  }
+};
+function createProxy(rootScope, value, parent, key) {
+  const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
+  const scope = parent?.scope_ ?? getCurrentScope();
+  scope.drafts_.push(draft);
+  state.callbacks_ = parent?.callbacks_ ?? [];
+  state.key_ = key;
+  if (parent && key !== void 0) {
+    registerChildFinalizationCallback(parent, state, key);
+  } else {
+    state.callbacks_.push(function rootDraftCleanup(rootScope2) {
+      rootScope2.mapSetPlugin_?.fixSetContents(state);
+      const { patchPlugin_ } = rootScope2;
+      if (state.modified_ && patchPlugin_) {
+        patchPlugin_.generatePatches_(state, [], rootScope2);
+      }
+    });
+  }
+  return draft;
+}
+
+// src/core/current.ts
+function current(value) {
+  if (!isDraft(value))
+    die(10, value);
+  return currentImpl(value);
+}
+function currentImpl(value) {
+  if (!isDraftable(value) || isFrozen(value))
+    return value;
+  const state = value[DRAFT_STATE];
+  let copy;
+  let strict = true;
+  if (state) {
+    if (!state.modified_)
+      return state.base_;
+    state.finalized_ = true;
+    copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
+    strict = state.scope_.immer_.shouldUseStrictIteration();
+  } else {
+    copy = shallowCopy(value, true);
+  }
+  each(
+    copy,
+    (key, childValue) => {
+      set(copy, key, currentImpl(childValue));
+    },
+    strict
+  );
+  if (state) {
+    state.finalized_ = false;
+  }
+  return copy;
+}
+
+// src/plugins/patches.ts
+function enablePatches() {
+  const errorOffset = 16;
+  if (process.env.NODE_ENV !== "production") {
+    errors.push(
+      'Sets cannot have "replace" patches.',
+      function(op) {
+        return "Unsupported patch operation: " + op;
+      },
+      function(path) {
+        return "Cannot apply patch, path doesn't resolve: " + path;
+      },
+      "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
+    );
+  }
+  function getPath(state, path = []) {
+    if (state.key_ !== void 0) {
+      const parentCopy = state.parent_.copy_ ?? state.parent_.base_;
+      const proxyDraft = getProxyDraft(get(parentCopy, state.key_));
+      const valueAtKey = get(parentCopy, state.key_);
+      if (valueAtKey === void 0) {
+        return null;
+      }
+      if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {
+        return null;
+      }
+      if (proxyDraft != null && proxyDraft.base_ !== state.base_) {
+        return null;
+      }
+      const isSet2 = state.parent_.type_ === 3 /* Set */;
+      let key;
+      if (isSet2) {
+        const setParent = state.parent_;
+        key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);
+      } else {
+        key = state.key_;
+      }
+      if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {
+        return null;
+      }
+      path.push(key);
+    }
+    if (state.parent_) {
+      return getPath(state.parent_, path);
+    }
+    path.reverse();
+    try {
+      resolvePath(state.copy_, path);
+    } catch (e) {
+      return null;
+    }
+    return path;
+  }
+  function resolvePath(base, path) {
+    let current2 = base;
+    for (let i = 0; i < path.length - 1; i++) {
+      const key = path[i];
+      current2 = get(current2, key);
+      if (!isObjectish(current2) || current2 === null) {
+        throw new Error(`Cannot resolve path at '${path.join("/")}'`);
+      }
+    }
+    return current2;
+  }
+  const REPLACE = "replace";
+  const ADD = "add";
+  const REMOVE = "remove";
+  function generatePatches_(state, basePath, scope) {
+    if (state.scope_.processedForPatches_.has(state)) {
+      return;
+    }
+    state.scope_.processedForPatches_.add(state);
+    const { patches_, inversePatches_ } = scope;
+    switch (state.type_) {
+      case 0 /* Object */:
+      case 2 /* Map */:
+        return generatePatchesFromAssigned(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+      case 1 /* Array */:
+        return generateArrayPatches(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+      case 3 /* Set */:
+        return generateSetPatches(
+          state,
+          basePath,
+          patches_,
+          inversePatches_
+        );
+    }
+  }
+  function generateArrayPatches(state, basePath, patches, inversePatches) {
+    let { base_, assigned_ } = state;
+    let copy_ = state.copy_;
+    if (copy_.length < base_.length) {
+      ;
+      [base_, copy_] = [copy_, base_];
+      [patches, inversePatches] = [inversePatches, patches];
+    }
+    const allReassigned = state.allIndicesReassigned_ === true;
+    for (let i = 0; i < base_.length; i++) {
+      const copiedItem = copy_[i];
+      const baseItem = base_[i];
+      const isAssigned = allReassigned || assigned_?.get(i.toString());
+      if (isAssigned && copiedItem !== baseItem) {
+        const childState = copiedItem?.[DRAFT_STATE];
+        if (childState && childState.modified_) {
+          continue;
+        }
+        const path = basePath.concat([i]);
+        patches.push({
+          op: REPLACE,
+          path,
+          // Need to maybe clone it, as it can in fact be the original value
+          // due to the base/copy inversion at the start of this function
+          value: clonePatchValueIfNeeded(copiedItem)
+        });
+        inversePatches.push({
+          op: REPLACE,
+          path,
+          value: clonePatchValueIfNeeded(baseItem)
+        });
+      }
+    }
+    for (let i = base_.length; i < copy_.length; i++) {
+      const path = basePath.concat([i]);
+      patches.push({
+        op: ADD,
+        path,
+        // Need to maybe clone it, as it can in fact be the original value
+        // due to the base/copy inversion at the start of this function
+        value: clonePatchValueIfNeeded(copy_[i])
+      });
+    }
+    for (let i = copy_.length - 1; base_.length <= i; --i) {
+      const path = basePath.concat([i]);
+      inversePatches.push({
+        op: REMOVE,
+        path
+      });
+    }
+  }
+  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
+    const { base_, copy_, type_ } = state;
+    each(state.assigned_, (key, assignedValue) => {
+      const origValue = get(base_, key, type_);
+      const value = get(copy_, key, type_);
+      const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
+      if (origValue === value && op === REPLACE)
+        return;
+      const path = basePath.concat(key);
+      patches.push(
+        op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }
+      );
+      inversePatches.push(
+        op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
+      );
+    });
+  }
+  function generateSetPatches(state, basePath, patches, inversePatches) {
+    let { base_, copy_ } = state;
+    let i = 0;
+    base_.forEach((value) => {
+      if (!copy_.has(value)) {
+        const path = basePath.concat([i]);
+        patches.push({
+          op: REMOVE,
+          path,
+          value
+        });
+        inversePatches.unshift({
+          op: ADD,
+          path,
+          value
+        });
+      }
+      i++;
+    });
+    i = 0;
+    copy_.forEach((value) => {
+      if (!base_.has(value)) {
+        const path = basePath.concat([i]);
+        patches.push({
+          op: ADD,
+          path,
+          value
+        });
+        inversePatches.unshift({
+          op: REMOVE,
+          path,
+          value
+        });
+      }
+      i++;
+    });
+  }
+  function generateReplacementPatches_(baseValue, replacement, scope) {
+    const { patches_, inversePatches_ } = scope;
+    patches_.push({
+      op: REPLACE,
+      path: [],
+      value: replacement === NOTHING ? void 0 : replacement
+    });
+    inversePatches_.push({
+      op: REPLACE,
+      path: [],
+      value: baseValue
+    });
+  }
+  function applyPatches_(draft, patches) {
+    patches.forEach((patch) => {
+      const { path, op } = patch;
+      let base = draft;
+      for (let i = 0; i < path.length - 1; i++) {
+        const parentType = getArchtype(base);
+        let p = path[i];
+        if (typeof p !== "string" && typeof p !== "number") {
+          p = "" + p;
+        }
+        if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === CONSTRUCTOR))
+          die(errorOffset + 3);
+        if (isFunction(base) && p === PROTOTYPE)
+          die(errorOffset + 3);
+        base = get(base, p);
+        if (!isObjectish(base))
+          die(errorOffset + 2, path.join("/"));
+      }
+      const type = getArchtype(base);
+      const value = deepClonePatchValue(patch.value);
+      const key = path[path.length - 1];
+      switch (op) {
+        case REPLACE:
+          switch (type) {
+            case 2 /* Map */:
+              return base.set(key, value);
+            case 3 /* Set */:
+              die(errorOffset);
+            default:
+              return base[key] = value;
+          }
+        case ADD:
+          switch (type) {
+            case 1 /* Array */:
+              return key === "-" ? base.push(value) : base.splice(key, 0, value);
+            case 2 /* Map */:
+              return base.set(key, value);
+            case 3 /* Set */:
+              return base.add(value);
+            default:
+              return base[key] = value;
+          }
+        case REMOVE:
+          switch (type) {
+            case 1 /* Array */:
+              return base.splice(key, 1);
+            case 2 /* Map */:
+              return base.delete(key);
+            case 3 /* Set */:
+              return base.delete(patch.value);
+            default:
+              return delete base[key];
+          }
+        default:
+          die(errorOffset + 1, op);
+      }
+    });
+    return draft;
+  }
+  function deepClonePatchValue(obj) {
+    if (!isDraftable(obj))
+      return obj;
+    if (isArray(obj))
+      return obj.map(deepClonePatchValue);
+    if (isMap(obj))
+      return new Map(
+        Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
+      );
+    if (isSet(obj))
+      return new Set(Array.from(obj).map(deepClonePatchValue));
+    const cloned = Object.create(getPrototypeOf(obj));
+    for (const key in obj)
+      cloned[key] = deepClonePatchValue(obj[key]);
+    if (has(obj, DRAFTABLE))
+      cloned[DRAFTABLE] = obj[DRAFTABLE];
+    return cloned;
+  }
+  function clonePatchValueIfNeeded(obj) {
+    if (isDraft(obj)) {
+      return deepClonePatchValue(obj);
+    } else
+      return obj;
+  }
+  loadPlugin(PluginPatches, {
+    applyPatches_,
+    generatePatches_,
+    generateReplacementPatches_,
+    getPath
+  });
+}
+
+// src/plugins/mapset.ts
+function enableMapSet() {
+  class DraftMap extends Map {
+    constructor(target, parent) {
+      super();
+      this[DRAFT_STATE] = {
+        type_: 2 /* Map */,
+        parent_: parent,
+        scope_: parent ? parent.scope_ : getCurrentScope(),
+        modified_: false,
+        finalized_: false,
+        copy_: void 0,
+        assigned_: void 0,
+        base_: target,
+        draft_: this,
+        isManual_: false,
+        revoked_: false,
+        callbacks_: []
+      };
+    }
+    get size() {
+      return latest(this[DRAFT_STATE]).size;
+    }
+    has(key) {
+      return latest(this[DRAFT_STATE]).has(key);
+    }
+    set(key, value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!latest(state).has(key) || latest(state).get(key) !== value) {
+        prepareMapCopy(state);
+        markChanged(state);
+        state.assigned_.set(key, true);
+        state.copy_.set(key, value);
+        state.assigned_.set(key, true);
+        handleCrossReference(state, key, value);
+      }
+      return this;
+    }
+    delete(key) {
+      if (!this.has(key)) {
+        return false;
+      }
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareMapCopy(state);
+      markChanged(state);
+      if (state.base_.has(key)) {
+        state.assigned_.set(key, false);
+      } else {
+        state.assigned_.delete(key);
+      }
+      state.copy_.delete(key);
+      return true;
+    }
+    clear() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (latest(state).size) {
+        prepareMapCopy(state);
+        markChanged(state);
+        state.assigned_ = /* @__PURE__ */ new Map();
+        each(state.base_, (key) => {
+          state.assigned_.set(key, false);
+        });
+        state.copy_.clear();
+      }
+    }
+    forEach(cb, thisArg) {
+      const state = this[DRAFT_STATE];
+      latest(state).forEach((_value, key, _map) => {
+        cb.call(thisArg, this.get(key), key, this);
+      });
+    }
+    get(key) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      const value = latest(state).get(key);
+      if (state.finalized_ || !isDraftable(value)) {
+        return value;
+      }
+      if (value !== state.base_.get(key)) {
+        return value;
+      }
+      const draft = createProxy(state.scope_, value, state, key);
+      prepareMapCopy(state);
+      state.copy_.set(key, draft);
+      return draft;
+    }
+    keys() {
+      return latest(this[DRAFT_STATE]).keys();
+    }
+    values() {
+      const iterator = this.keys();
+      return {
+        [Symbol.iterator]: () => this.values(),
+        next: () => {
+          const r = iterator.next();
+          if (r.done)
+            return r;
+          const value = this.get(r.value);
+          return {
+            done: false,
+            value
+          };
+        }
+      };
+    }
+    entries() {
+      const iterator = this.keys();
+      return {
+        [Symbol.iterator]: () => this.entries(),
+        next: () => {
+          const r = iterator.next();
+          if (r.done)
+            return r;
+          const value = this.get(r.value);
+          return {
+            done: false,
+            value: [r.value, value]
+          };
+        }
+      };
+    }
+    [(DRAFT_STATE, Symbol.iterator)]() {
+      return this.entries();
+    }
+  }
+  function proxyMap_(target, parent) {
+    const map = new DraftMap(target, parent);
+    return [map, map[DRAFT_STATE]];
+  }
+  function prepareMapCopy(state) {
+    if (!state.copy_) {
+      state.assigned_ = /* @__PURE__ */ new Map();
+      state.copy_ = new Map(state.base_);
+    }
+  }
+  class DraftSet extends Set {
+    constructor(target, parent) {
+      super();
+      this[DRAFT_STATE] = {
+        type_: 3 /* Set */,
+        parent_: parent,
+        scope_: parent ? parent.scope_ : getCurrentScope(),
+        modified_: false,
+        finalized_: false,
+        copy_: void 0,
+        base_: target,
+        draft_: this,
+        drafts_: /* @__PURE__ */ new Map(),
+        revoked_: false,
+        isManual_: false,
+        assigned_: void 0,
+        callbacks_: []
+      };
+    }
+    get size() {
+      return latest(this[DRAFT_STATE]).size;
+    }
+    has(value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!state.copy_) {
+        return state.base_.has(value);
+      }
+      if (state.copy_.has(value))
+        return true;
+      if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))
+        return true;
+      return false;
+    }
+    add(value) {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (!this.has(value)) {
+        prepareSetCopy(state);
+        markChanged(state);
+        state.copy_.add(value);
+        handleCrossReference(state, value, value);
+      }
+      return this;
+    }
+    delete(value) {
+      if (!this.has(value)) {
+        return false;
+      }
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      markChanged(state);
+      return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (
+        /* istanbul ignore next */
+        false
+      ));
+    }
+    clear() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      if (latest(state).size) {
+        prepareSetCopy(state);
+        markChanged(state);
+        state.copy_.clear();
+      }
+    }
+    values() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      return state.copy_.values();
+    }
+    entries() {
+      const state = this[DRAFT_STATE];
+      assertUnrevoked(state);
+      prepareSetCopy(state);
+      return state.copy_.entries();
+    }
+    keys() {
+      return this.values();
+    }
+    [(DRAFT_STATE, Symbol.iterator)]() {
+      return this.values();
+    }
+    forEach(cb, thisArg) {
+      const iterator = this.values();
+      let result = iterator.next();
+      while (!result.done) {
+        cb.call(thisArg, result.value, result.value, this);
+        result = iterator.next();
+      }
+    }
+  }
+  function proxySet_(target, parent) {
+    const set2 = new DraftSet(target, parent);
+    return [set2, set2[DRAFT_STATE]];
+  }
+  function prepareSetCopy(state) {
+    if (!state.copy_) {
+      state.copy_ = /* @__PURE__ */ new Set();
+      state.base_.forEach((value) => {
+        if (isDraftable(value)) {
+          const draft = createProxy(state.scope_, value, state, value);
+          state.drafts_.set(value, draft);
+          state.copy_.add(draft);
+        } else {
+          state.copy_.add(value);
+        }
+      });
+    }
+  }
+  function assertUnrevoked(state) {
+    if (state.revoked_)
+      die(3, JSON.stringify(latest(state)));
+  }
+  function fixSetContents(target) {
+    if (target.type_ === 3 /* Set */ && target.copy_) {
+      const copy = new Set(target.copy_);
+      target.copy_.clear();
+      copy.forEach((value) => {
+        target.copy_.add(getValue(value));
+      });
+    }
+  }
+  loadPlugin(PluginMapSet, { proxyMap_, proxySet_, fixSetContents });
+}
+
+// src/plugins/arrayMethods.ts
+function enableArrayMethods() {
+  const SHIFTING_METHODS = /* @__PURE__ */ new Set(["shift", "unshift"]);
+  const QUEUE_METHODS = /* @__PURE__ */ new Set(["push", "pop"]);
+  const RESULT_RETURNING_METHODS = /* @__PURE__ */ new Set([
+    ...QUEUE_METHODS,
+    ...SHIFTING_METHODS
+  ]);
+  const REORDERING_METHODS = /* @__PURE__ */ new Set(["reverse", "sort"]);
+  const MUTATING_METHODS = /* @__PURE__ */ new Set([
+    ...RESULT_RETURNING_METHODS,
+    ...REORDERING_METHODS,
+    "splice"
+  ]);
+  const FIND_METHODS = /* @__PURE__ */ new Set(["find", "findLast"]);
+  const NON_MUTATING_METHODS = /* @__PURE__ */ new Set([
+    "filter",
+    "slice",
+    "concat",
+    "flat",
+    ...FIND_METHODS,
+    "findIndex",
+    "findLastIndex",
+    "some",
+    "every",
+    "indexOf",
+    "lastIndexOf",
+    "includes",
+    "join",
+    "toString",
+    "toLocaleString"
+  ]);
+  function isMutatingArrayMethod(method) {
+    return MUTATING_METHODS.has(method);
+  }
+  function isNonMutatingArrayMethod(method) {
+    return NON_MUTATING_METHODS.has(method);
+  }
+  function isArrayOperationMethod(method) {
+    return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method);
+  }
+  function enterOperation(state, method) {
+    state.operationMethod = method;
+  }
+  function exitOperation(state) {
+    state.operationMethod = void 0;
+  }
+  function executeArrayMethod(state, operation, markLength = true) {
+    prepareCopy(state);
+    const result = operation();
+    markChanged(state);
+    if (markLength)
+      state.assigned_.set("length", true);
+    return result;
+  }
+  function markAllIndicesReassigned(state) {
+    state.allIndicesReassigned_ = true;
+  }
+  function normalizeSliceIndex(index, length) {
+    if (index < 0) {
+      return Math.max(length + index, 0);
+    }
+    return Math.min(index, length);
+  }
+  function handleSimpleOperation(state, method, args) {
+    return executeArrayMethod(state, () => {
+      const result = state.copy_[method](...args);
+      if (SHIFTING_METHODS.has(method)) {
+        markAllIndicesReassigned(state);
+      }
+      return RESULT_RETURNING_METHODS.has(method) ? result : state.draft_;
+    });
+  }
+  function handleReorderingOperation(state, method, args) {
+    return executeArrayMethod(
+      state,
+      () => {
+        ;
+        state.copy_[method](...args);
+        markAllIndicesReassigned(state);
+        return state.draft_;
+      },
+      false
+    );
+  }
+  function createMethodInterceptor(state, originalMethod) {
+    return function interceptedMethod(...args) {
+      const method = originalMethod;
+      enterOperation(state, method);
+      try {
+        if (isMutatingArrayMethod(method)) {
+          if (RESULT_RETURNING_METHODS.has(method)) {
+            return handleSimpleOperation(state, method, args);
+          }
+          if (REORDERING_METHODS.has(method)) {
+            return handleReorderingOperation(state, method, args);
+          }
+          if (method === "splice") {
+            const res = executeArrayMethod(
+              state,
+              () => state.copy_.splice(...args)
+            );
+            markAllIndicesReassigned(state);
+            return res;
+          }
+        } else {
+          return handleNonMutatingOperation(state, method, args);
+        }
+      } finally {
+        exitOperation(state);
+      }
+    };
+  }
+  function handleNonMutatingOperation(state, method, args) {
+    const source = latest(state);
+    if (method === "filter") {
+      const predicate = args[0];
+      const result = [];
+      for (let i = 0; i < source.length; i++) {
+        if (predicate(source[i], i, source)) {
+          result.push(state.draft_[i]);
+        }
+      }
+      return result;
+    }
+    if (FIND_METHODS.has(method)) {
+      const predicate = args[0];
+      const isForward = method === "find";
+      const step = isForward ? 1 : -1;
+      const start = isForward ? 0 : source.length - 1;
+      for (let i = start; i >= 0 && i < source.length; i += step) {
+        if (predicate(source[i], i, source)) {
+          return state.draft_[i];
+        }
+      }
+      return void 0;
+    }
+    if (method === "slice") {
+      const rawStart = args[0] ?? 0;
+      const rawEnd = args[1] ?? source.length;
+      const start = normalizeSliceIndex(rawStart, source.length);
+      const end = normalizeSliceIndex(rawEnd, source.length);
+      const result = [];
+      for (let i = start; i < end; i++) {
+        result.push(state.draft_[i]);
+      }
+      return result;
+    }
+    return source[method](...args);
+  }
+  loadPlugin(PluginArrayMethods, {
+    createMethodInterceptor,
+    isArrayOperationMethod,
+    isMutatingArrayMethod
+  });
+}
+
+// src/immer.ts
+var immer = new Immer2();
+var produce = immer.produce;
+var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(
+  immer
+);
+var setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer);
+var setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(
+  immer
+);
+var setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(
+  immer
+);
+var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
+var createDraft = /* @__PURE__ */ immer.createDraft.bind(immer);
+var finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer);
+var castDraft = (value) => value;
+var castImmutable = (value) => value;
+export {
+  Immer2 as Immer,
+  applyPatches,
+  castDraft,
+  castImmutable,
+  createDraft,
+  current,
+  enableArrayMethods,
+  enableMapSet,
+  enablePatches,
+  finishDraft,
+  freeze,
+  DRAFTABLE as immerable,
+  isDraft,
+  isDraftable,
+  NOTHING as nothing,
+  original,
+  produce,
+  produceWithPatches,
+  setAutoFreeze,
+  setUseStrictIteration,
+  setUseStrictShallowCopy
+};
+//# sourceMappingURL=immer.mjs.map
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../src/utils/env.ts","../src/utils/errors.ts","../src/utils/common.ts","../src/utils/plugins.ts","../src/core/scope.ts","../src/core/finalize.ts","../src/core/proxy.ts","../src/core/immerClass.ts","../src/core/current.ts","../src/plugins/patches.ts","../src/plugins/mapset.ts","../src/plugins/arrayMethods.ts","../src/immer.ts"],"sourcesContent":["// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","import {isFunction} from \"../internal\"\n\nexport const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t  ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = isFunction(e) ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nconst O = Object\n\nexport const getPrototypeOf = O.getPrototypeOf\n\nexport const CONSTRUCTOR = \"constructor\"\nexport const PROTOTYPE = \"prototype\"\n\nexport const CONFIGURABLE = \"configurable\"\nexport const ENUMERABLE = \"enumerable\"\nexport const WRITABLE = \"writable\"\nexport const VALUE = \"value\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tisArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value[CONSTRUCTOR]?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()\nconst cachedCtorStrings = new WeakMap()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || !isObjectish(value)) return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null || proto === O[PROTOTYPE]) return true\n\n\tconst Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]\n\tif (Ctor === Object) return true\n\n\tif (!isFunction(Ctor)) return false\n\n\tlet ctorString = cachedCtorStrings.get(Ctor)\n\tif (ctorString === undefined) {\n\t\tctorString = Function.toString.call(Ctor)\n\t\tcachedCtorStrings.set(Ctor, ctorString)\n\t}\n\n\treturn ctorString === objectCtorString\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n *\n * @param obj The object to iterate over\n * @param iter The iterator function\n * @param strict When true (default), includes symbols and non-enumerable properties.\n *               When false, uses looseiteration over only enumerable string properties.\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tstrict?: boolean\n): void\nexport function each(obj: any, iter: any, strict: boolean = true) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\t// If strict, we do a full iteration including symbols and non-enumerable properties\n\t\t// Otherwise, we only iterate enumerable string properties for performance\n\t\tconst keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)\n\t\tkeys.forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport let has = (\n\tthing: any,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): boolean =>\n\ttype === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: O[PROTOTYPE].hasOwnProperty.call(thing, prop)\n\n/*#__PURE__*/\nexport let get = (\n\tthing: AnyMap | AnyObject,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): any =>\n\t// @ts-ignore\n\ttype === ArchType.Map ? thing.get(prop) : thing[prop]\n\n/*#__PURE__*/\nexport let set = (\n\tthing: any,\n\tpropOrOldValue: PropertyKey,\n\tvalue: any,\n\ttype = getArchtype(thing)\n) => {\n\tif (type === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (type === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\nexport let isArray = Array.isArray\n\n/*#__PURE__*/\nexport let isMap = (target: any): target is AnyMap => target instanceof Map\n\n/*#__PURE__*/\nexport let isSet = (target: any): target is AnySet => target instanceof Set\n\nexport let isObjectish = (target: any) => typeof target === \"object\"\n\nexport let isFunction = (target: any): target is Function =>\n\ttypeof target === \"function\"\n\nexport let isBoolean = (target: any): target is boolean =>\n\ttypeof target === \"boolean\"\n\nexport function isArrayIndex(value: string | number): value is number | string {\n\tconst n = +value\n\treturn Number.isInteger(n) && String(n) === value\n}\n\nexport let getProxyDraft = <T extends any>(value: T): ImmerState | null => {\n\tif (!isObjectish(value)) return null\n\treturn (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]\n}\n\n/*#__PURE__*/\nexport let latest = (state: ImmerState): any => state.copy_ || state.base_\n\nexport let getValue = <T extends object>(value: T): T => {\n\tconst proxyDraft = getProxyDraft(value)\n\treturn proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value\n}\n\nexport let getFinalValue = (state: ImmerState): any =>\n\tstate.modified_ ? state.copy_ : state.base_\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (isArray(base)) return Array[PROTOTYPE].slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = O.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc[WRITABLE] === false) {\n\t\t\t\tdesc[WRITABLE] = true\n\t\t\t\tdesc[CONFIGURABLE] = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\t[CONFIGURABLE]: true,\n\t\t\t\t\t[WRITABLE]: true, // could live with !!desc.set as well here...\n\t\t\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t\t\t[VALUE]: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn O.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = O.create(proto)\n\t\treturn O.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tO.defineProperties(obj, {\n\t\t\tset: dontMutateMethodOverride,\n\t\t\tadd: dontMutateMethodOverride,\n\t\t\tclear: dontMutateMethodOverride,\n\t\t\tdelete: dontMutateMethodOverride\n\t\t})\n\t}\n\tO.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.values (only string-like, enumerables) instead of each()\n\t\teach(\n\t\t\tobj,\n\t\t\t(_key, value) => {\n\t\t\t\tfreeze(value, true)\n\t\t\t},\n\t\t\tfalse\n\t\t)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nconst dontMutateMethodOverride = {\n\t[VALUE]: dontMutateFrozenCollections\n}\n\nexport function isFrozen(obj: any): boolean {\n\t// Fast path: primitives and null/undefined are always \"frozen\"\n\tif (obj === null || !isObjectish(obj)) return true\n\treturn O.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie,\n\tImmerScope,\n\tProxyArrayState\n} from \"../internal\"\n\nexport const PluginMapSet = \"MapSet\"\nexport const PluginPatches = \"Patches\"\nexport const PluginArrayMethods = \"ArrayMethods\"\n\nexport type PatchesPlugin = {\n\tgeneratePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\trootScope: ImmerScope\n\t): void\n\tgenerateReplacementPatches_(\n\t\tbase: any,\n\t\treplacement: any,\n\t\trootScope: ImmerScope\n\t): void\n\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\tgetPath: (state: ImmerState) => PatchPath | null\n}\n\nexport type MapSetPlugin = {\n\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]\n\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]\n\tfixSetContents: (state: ImmerState) => void\n}\n\nexport type ArrayMethodsPlugin = {\n\tcreateMethodInterceptor: (state: ProxyArrayState, method: string) => Function\n\tisArrayOperationMethod: (method: string) => boolean\n\tisMutatingArrayMethod: (method: string) => boolean\n}\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: PatchesPlugin\n\tMapSet?: MapSetPlugin\n\tArrayMethods?: ArrayMethodsPlugin\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>\n\t!!plugins[pluginKey]\n\nexport let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {\n\tdelete plugins[pluginKey]\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin,\n\tPatchesPlugin,\n\tMapSetPlugin,\n\tisPluginLoaded,\n\tPluginMapSet,\n\tPluginPatches,\n\tArrayMethodsPlugin,\n\tPluginArrayMethods\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tpatchPlugin_?: PatchesPlugin\n\tmapSetPlugin_?: MapSetPlugin\n\tarrayMethodsPlugin_?: ArrayMethodsPlugin\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n\thandledSet_: Set<any>\n\tprocessedForPatches_: Set<any>\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport let getCurrentScope = () => currentScope!\n\nlet createScope = (\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope => ({\n\tdrafts_: [],\n\tparent_,\n\timmer_,\n\t// Whenever the modified draft contains a draft from another scope, we\n\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\tcanAutoFreeze_: true,\n\tunfinalizedDrafts_: 0,\n\thandledSet_: new Set(),\n\tprocessedForPatches_: new Set(),\n\tmapSetPlugin_: isPluginLoaded(PluginMapSet)\n\t\t? getPlugin(PluginMapSet)\n\t\t: undefined,\n\tarrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods)\n\t\t? getPlugin(PluginArrayMethods)\n\t\t: undefined\n})\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tscope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport let enterScope = (immer: Immer) =>\n\t(currentScope = createScope(currentScope, immer))\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tget,\n\tPatch,\n\tlatest,\n\tprepareCopy,\n\tgetFinalValue,\n\tgetValue,\n\tProxyArrayState\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t}\n\t\tconst {patchPlugin_} = scope\n\t\tif (patchPlugin_) {\n\t\t\tpatchPlugin_.generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft)\n\t}\n\n\tmaybeFreeze(scope, result, true)\n\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\tif (!state) {\n\t\tconst finalValue = handleValue(value, rootScope.handledSet_, rootScope)\n\t\treturn finalValue\n\t}\n\n\t// Never finalize drafts owned by another scope\n\tif (!isSameScope(state, rootScope)) {\n\t\treturn value\n\t}\n\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\treturn state.base_\n\t}\n\n\tif (!state.finalized_) {\n\t\t// Execute all registered draft finalization callbacks\n\t\tconst {callbacks_} = state\n\t\tif (callbacks_) {\n\t\t\twhile (callbacks_.length > 0) {\n\t\t\t\tconst callback = callbacks_.pop()!\n\t\t\t\tcallback(rootScope)\n\t\t\t}\n\t\t}\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t}\n\n\t// By now the root copy has been fully updated throughout its tree\n\treturn state.copy_\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n\nfunction markStateFinalized(state: ImmerState) {\n\tstate.finalized_ = true\n\tstate.scope_.unfinalizedDrafts_--\n}\n\nlet isSameScope = (state: ImmerState, rootScope: ImmerScope) =>\n\tstate.scope_ === rootScope\n\n// A reusable empty array to avoid allocations\nconst EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []\n\n// Updates all references to a draft in its parent to the finalized value.\n// This handles cases where the same draft appears multiple times in the parent, or has been moved around.\nexport function updateDraftInParent(\n\tparent: ImmerState,\n\tdraftValue: any,\n\tfinalizedValue: any,\n\toriginalKey?: string | number | symbol\n): void {\n\tconst parentCopy = latest(parent)\n\tconst parentType = parent.type_\n\n\t// Fast path: Check if draft is still at original key\n\tif (originalKey !== undefined) {\n\t\tconst currentValue = get(parentCopy, originalKey, parentType)\n\t\tif (currentValue === draftValue) {\n\t\t\t// Still at original location, just update it\n\t\t\tset(parentCopy, originalKey, finalizedValue, parentType)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Slow path: Build reverse mapping of all children\n\t// to their indices in the parent, so that we can\n\t// replace all locations where this draft appears.\n\t// We only have to build this once per parent.\n\tif (!parent.draftLocations_) {\n\t\tconst draftLocations = (parent.draftLocations_ = new Map())\n\n\t\t// Use `each` which works on Arrays, Maps, and Objects\n\t\teach(parentCopy, (key, value) => {\n\t\t\tif (isDraft(value)) {\n\t\t\t\tconst keys = draftLocations.get(value) || []\n\t\t\t\tkeys.push(key)\n\t\t\t\tdraftLocations.set(value, keys)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Look up all locations where this draft appears\n\tconst locations =\n\t\tparent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT\n\n\t// Update all locations\n\tfor (const location of locations) {\n\t\tset(parentCopy, location, finalizedValue, parentType)\n\t}\n}\n\n// Register a callback to finalize a child draft when the parent draft is finalized.\n// This assumes there is a parent -> child relationship between the two drafts,\n// and we have a key to locate the child in the parent.\nexport function registerChildFinalizationCallback(\n\tparent: ImmerState,\n\tchild: ImmerState,\n\tkey: string | number | symbol\n) {\n\tparent.callbacks_.push(function childCleanup(rootScope) {\n\t\tconst state: ImmerState = child\n\n\t\t// Can only continue if this is a draft owned by this scope\n\t\tif (!state || !isSameScope(state, rootScope)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle potential set value finalization first\n\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t// Update all locations in the parent that referenced this draft\n\t\tupdateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t})\n}\n\nfunction generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {\n\tconst shouldFinalize =\n\t\tstate.modified_ &&\n\t\t!state.finalized_ &&\n\t\t(state.type_ === ArchType.Set ||\n\t\t\t(state.type_ === ArchType.Array &&\n\t\t\t\t(state as ProxyArrayState).allIndicesReassigned_) ||\n\t\t\t(state.assigned_?.size ?? 0) > 0)\n\n\tif (shouldFinalize) {\n\t\tconst {patchPlugin_} = rootScope\n\t\tif (patchPlugin_) {\n\t\t\tconst basePath = patchPlugin_!.getPath(state)\n\n\t\t\tif (basePath) {\n\t\t\t\tpatchPlugin_!.generatePatches_(state, basePath, rootScope)\n\t\t\t}\n\t\t}\n\n\t\tmarkStateFinalized(state)\n\t}\n}\n\nexport function handleCrossReference(\n\ttarget: ImmerState,\n\tkey: string | number | symbol,\n\tvalue: any\n) {\n\tconst {scope_} = target\n\t// Check if value is a draft from this scope\n\tif (isDraft(value)) {\n\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\tif (isSameScope(state, scope_)) {\n\t\t\t// Register callback to update this location when the draft finalizes\n\n\t\t\tstate.callbacks_.push(function crossReferenceCleanup() {\n\t\t\t\t// Update the target location with finalized value\n\t\t\t\tprepareCopy(target)\n\n\t\t\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t\t\tupdateDraftInParent(target, value, finalizedValue, key)\n\t\t\t})\n\t\t}\n\t} else if (isDraftable(value)) {\n\t\t// Handle non-draft objects that might contain drafts\n\t\ttarget.callbacks_.push(function nestedDraftCleanup() {\n\t\t\tconst targetCopy = latest(target)\n\n\t\t\t// For Sets, check if value is still in the set\n\t\t\tif (target.type_ === ArchType.Set) {\n\t\t\t\tif (targetCopy.has(value)) {\n\t\t\t\t\t// Process the value to replace any nested drafts\n\t\t\t\t\thandleValue(value, scope_.handledSet_, scope_)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Maps/objects\n\t\t\t\tif (get(targetCopy, key, target.type_) === value) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tscope_.drafts_.length > 1 &&\n\t\t\t\t\t\t((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??\n\t\t\t\t\t\t\tfalse) === true &&\n\t\t\t\t\t\ttarget.copy_\n\t\t\t\t\t) {\n\t\t\t\t\t\t// This might be a non-draft value that has drafts\n\t\t\t\t\t\t// inside. We do need to recurse here to handle those.\n\t\t\t\t\t\thandleValue(\n\t\t\t\t\t\t\tget(target.copy_, key, target.type_),\n\t\t\t\t\t\t\tscope_.handledSet_,\n\t\t\t\t\t\t\tscope_\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nexport function handleValue(\n\ttarget: any,\n\thandledSet: Set<any>,\n\trootScope: ImmerScope\n) {\n\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t// This benefits especially adding large data tree's without further processing.\n\t\t// See add-data.js perf test\n\t\treturn target\n\t}\n\n\t// Skip if already handled, frozen, or not draftable\n\tif (\n\t\tisDraft(target) ||\n\t\thandledSet.has(target) ||\n\t\t!isDraftable(target) ||\n\t\tisFrozen(target)\n\t) {\n\t\treturn target\n\t}\n\n\thandledSet.add(target)\n\n\t// Process ALL properties/entries\n\teach(target, (key, value) => {\n\t\tif (isDraft(value)) {\n\t\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\t\tif (isSameScope(state, rootScope)) {\n\t\t\t\t// Replace draft with finalized value\n\n\t\t\t\tconst updatedValue = getFinalValue(state)\n\n\t\t\t\tset(target, key, updatedValue, target.type_)\n\n\t\t\t\tmarkStateFinalized(state)\n\t\t\t}\n\t\t} else if (isDraftable(value)) {\n\t\t\t// Recursively handle nested values\n\t\t\thandleValue(value, handledSet, rootScope)\n\t\t}\n\t})\n\n\treturn target\n}\n","import {\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\thandleCrossReference,\n\tWRITABLE,\n\tCONFIGURABLE,\n\tENUMERABLE,\n\tVALUE,\n\tisArray,\n\tisArrayIndex\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n\toperationMethod?: string\n\tallIndicesReassigned_?: boolean\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): [Drafted<T, ProxyState>, ProxyState] {\n\tconst baseIsArray = isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: baseIsArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\t// actually instantiated in `prepareCopy()`\n\t\tassigned_: undefined,\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false,\n\t\t// `callbacks` actually gets assigned in `createProxy`\n\t\tcallbacks_: undefined as any\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (baseIsArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn [proxy as any, state]\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tlet arrayPlugin = state.scope_.arrayMethodsPlugin_\n\t\tconst isArrayWithStringProp =\n\t\t\tstate.type_ === ArchType.Array && typeof prop === \"string\"\n\t\t// Intercept array methods so that we can override\n\t\t// behavior and skip proxy creation for perf\n\t\tif (isArrayWithStringProp) {\n\t\t\tif (arrayPlugin?.isArrayOperationMethod(prop)) {\n\t\t\t\treturn arrayPlugin.createMethodInterceptor(state, prop)\n\t\t\t}\n\t\t}\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop, state.type_)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\t// During mutating array operations, defer proxy creation for array elements\n\t\t// This optimization avoids creating unnecessary proxies during sort/reverse\n\t\tif (\n\t\t\tisArrayWithStringProp &&\n\t\t\t(state as ProxyArrayState).operationMethod &&\n\t\t\tarrayPlugin?.isMutatingArrayMethod(\n\t\t\t\t(state as ProxyArrayState).operationMethod!\n\t\t\t) &&\n\t\t\tisArrayIndex(prop)\n\t\t) {\n\t\t\t// Return raw value during mutating operations, create proxy only if modified\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\t// Ensure array keys are always numbers\n\t\t\tconst childKey = state.type_ === ArchType.Array ? +(prop as string) : prop\n\t\t\tconst childDraft = createProxy(state.scope_, value, state, childKey)\n\n\t\t\treturn (state.copy_![childKey] = childDraft)\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_!.set(prop, false)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (\n\t\t\t\tis(value, current) &&\n\t\t\t\t(value !== undefined || has(state.base_, prop, state.type_))\n\t\t\t)\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_!.set(prop, true)\n\n\t\thandleCrossReference(state, prop, value)\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\tprepareCopy(state)\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_!.set(prop, false)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tstate.assigned_!.delete(prop)\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\t[WRITABLE]: true,\n\t\t\t[CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t[VALUE]: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\n// Use `for..in` instead of `each` to work around a weird\n// prod test suite issue\nfor (let key in objectTraps) {\n\tlet fn = objectTraps[key as keyof typeof objectTraps] as Function\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\tconst args = arguments\n\t\targs[0] = args[0][0]\n\t\treturn fn.apply(this, args)\n\t}\n}\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? VALUE in desc\n\t\t\t? desc[VALUE]\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t  // prototype, we should invoke it with the draft as context!\n\t\t\t  desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: ImmerState) {\n\tif (!state.copy_) {\n\t\t// Actually create the `assigned_` map now that we\n\t\t// know this is a modified draft.\n\t\tstate.assigned_ = new Map()\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent,\n\tImmerScope,\n\tregisterChildFinalizationCallback,\n\tArchType,\n\tMapSetPlugin,\n\tAnyMap,\n\tAnySet,\n\tisObjectish,\n\tisFunction,\n\tisBoolean,\n\tPluginMapSet,\n\tPluginPatches\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\"\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\tuseStrictIteration_: boolean = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t\tuseStrictIteration?: boolean\n\t}) {\n\t\tif (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)\n\t\tif (isBoolean(config?.useStrictShallowCopy))\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t\tif (isBoolean(config?.useStrictIteration))\n\t\t\tthis.setUseStrictIteration(config!.useStrictIteration)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (isFunction(base) && !isFunction(recipe)) {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (!isFunction(recipe)) die(6)\n\t\tif (patchListener !== undefined && !isFunction(patchListener)) die(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(scope, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || !isObjectish(base)) {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n\t\t\t\t\tpatches_: p,\n\t\t\t\t\tinversePatches_: ip\n\t\t\t\t} as ImmerScope) // dummy scope\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (isFunction(base)) {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(scope, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\t/**\n\t * Pass false to use faster iteration that skips non-enumerable properties\n\t * but still handles symbols for compatibility.\n\t *\n\t * By default, strict iteration is enabled (includes all own properties).\n\t */\n\tsetUseStrictIteration(value: boolean) {\n\t\tthis.useStrictIteration_ = value\n\t}\n\n\tshouldUseStrictIteration(): boolean {\n\t\treturn this.useStrictIteration_\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(PluginPatches).applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\trootScope: ImmerScope,\n\tvalue: T,\n\tparent?: ImmerState,\n\tkey?: string | number | symbol\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\t// returning a tuple here lets us skip a proxy access\n\t// to DRAFT_STATE later\n\tconst [draft, state] = isMap(value)\n\t\t? getPlugin(PluginMapSet).proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(PluginMapSet).proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent?.scope_ ?? getCurrentScope()\n\tscope.drafts_.push(draft)\n\n\t// Ensure the parent callbacks are passed down so we actually\n\t// track all callbacks added throughout the tree\n\tstate.callbacks_ = parent?.callbacks_ ?? []\n\tstate.key_ = key\n\n\tif (parent && key !== undefined) {\n\t\tregisterChildFinalizationCallback(parent, state, key)\n\t} else {\n\t\t// It's a root draft, register it with the scope\n\t\tstate.callbacks_.push(function rootDraftCleanup(rootScope) {\n\t\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\t\tconst {patchPlugin_} = rootScope\n\n\t\t\tif (state.modified_ && patchPlugin_) {\n\t\t\t\tpatchPlugin_.generatePatches_(state, [], rootScope)\n\t\t\t}\n\t\t})\n\t}\n\n\treturn draft as any\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tlet strict = true // Default to strict for compatibility\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t\tstrict = state.scope_.immer_.shouldUseStrictIteration()\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(\n\t\tcopy,\n\t\t(key, childValue) => {\n\t\t\tset(copy, key, currentImpl(childValue))\n\t\t},\n\t\tstrict\n\t)\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors,\n\tDRAFT_STATE,\n\tgetProxyDraft,\n\tImmerScope,\n\tisObjectish,\n\tisFunction,\n\tCONSTRUCTOR,\n\tPluginPatches,\n\tisArray,\n\tPROTOTYPE\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tfunction getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {\n\t\t// Step 1: Check if state has a stored key\n\t\tif (state.key_ !== undefined) {\n\t\t\t// Step 2: Validate the key is still valid in parent\n\n\t\t\tconst parentCopy = state.parent_!.copy_ ?? state.parent_!.base_\n\t\t\tconst proxyDraft = getProxyDraft(get(parentCopy, state.key_!))\n\t\t\tconst valueAtKey = get(parentCopy, state.key_!)\n\n\t\t\tif (valueAtKey === undefined) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Check if the value at the key is still related to this draft\n\t\t\t// It should be either the draft itself, the base, or the copy\n\t\t\tif (\n\t\t\t\tvalueAtKey !== state.draft_ &&\n\t\t\t\tvalueAtKey !== state.base_ &&\n\t\t\t\tvalueAtKey !== state.copy_\n\t\t\t) {\n\t\t\t\treturn null // Value was replaced with something else\n\t\t\t}\n\t\t\tif (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n\t\t\t\treturn null // Different draft\n\t\t\t}\n\n\t\t\t// Step 3: Handle Set case specially\n\t\t\tconst isSet = state.parent_!.type_ === ArchType.Set\n\t\t\tlet key: string | number\n\n\t\t\tif (isSet) {\n\t\t\t\t// For Sets, find the index in the drafts_ map\n\t\t\t\tconst setParent = state.parent_ as SetState\n\t\t\t\tkey = Array.from(setParent.drafts_.keys()).indexOf(state.key_)\n\t\t\t} else {\n\t\t\t\tkey = state.key_ as string | number\n\t\t\t}\n\n\t\t\t// Step 4: Validate key still exists in parent\n\t\t\tif (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {\n\t\t\t\treturn null // Key deleted\n\t\t\t}\n\n\t\t\t// Step 5: Add key to path\n\t\t\tpath.push(key)\n\t\t}\n\n\t\t// Step 6: Recurse to parent if exists\n\t\tif (state.parent_) {\n\t\t\treturn getPath(state.parent_, path)\n\t\t}\n\n\t\t// Step 7: At root - reverse path and validate\n\t\tpath.reverse()\n\n\t\ttry {\n\t\t\t// Validate path can be resolved from ROOT\n\t\t\tresolvePath(state.copy_, path)\n\t\t} catch (e) {\n\t\t\treturn null // Path invalid\n\t\t}\n\n\t\treturn path\n\t}\n\n\t// NEW: Add resolvePath helper function\n\tfunction resolvePath(base: any, path: PatchPath): any {\n\t\tlet current = base\n\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\tconst key = path[i]\n\t\t\tcurrent = get(current, key)\n\t\t\tif (!isObjectish(current) || current === null) {\n\t\t\t\tthrow new Error(`Cannot resolve path at '${path.join(\"/\")}'`)\n\t\t\t}\n\t\t}\n\t\treturn current\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tscope: ImmerScope\n\t): void {\n\t\tif (state.scope_.processedForPatches_.has(state)) {\n\t\t\treturn\n\t\t}\n\n\t\tstate.scope_.processedForPatches_.add(state)\n\n\t\tconst {patches_, inversePatches_} = scope\n\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\tconst allReassigned = state.allIndicesReassigned_ === true\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tconst copiedItem = copy_[i]\n\t\t\tconst baseItem = base_[i]\n\n\t\t\tconst isAssigned = allReassigned || assigned_?.get(i.toString())\n\t\t\tif (isAssigned && copiedItem !== baseItem) {\n\t\t\t\tconst childState = copiedItem?.[DRAFT_STATE]\n\t\t\t\tif (childState && childState.modified_) {\n\t\t\t\t\t// Skip - let the child generate its own patches\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copiedItem)\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(baseItem)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_, type_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key, type_)\n\t\t\tconst value = get(copy_!, key, type_)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(\n\t\t\t\top === REMOVE\n\t\t\t\t\t? {op, path}\n\t\t\t\t\t: {op, path, value: clonePatchValueIfNeeded(value)}\n\t\t\t)\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tscope: ImmerScope\n\t): void {\n\t\tconst {patches_, inversePatches_} = scope\n\t\tpatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === CONSTRUCTOR)\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (!isObjectish(base)) die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(PluginPatches, {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_,\n\t\tgetPath\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach,\n\tgetValue,\n\tPluginMapSet,\n\thandleCrossReference\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\thandleCrossReference(state, key, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_, value, state, key)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, MapState] {\n\t\t// @ts-ignore\n\t\tconst map = new DraftMap(target, parent)\n\t\treturn [map as any, map[DRAFT_STATE]]\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t\thandleCrossReference(state, value, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, SetState] {\n\t\t// @ts-ignore\n\t\tconst set = new DraftSet(target, parent)\n\t\treturn [set as any, set[DRAFT_STATE]]\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_, value, state, value)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tfunction fixSetContents(target: ImmerState) {\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\tif (target.type_ === ArchType.Set && target.copy_) {\n\t\t\tconst copy = new Set(target.copy_)\n\t\t\ttarget.copy_.clear()\n\t\t\tcopy.forEach(value => {\n\t\t\t\ttarget.copy_!.add(getValue(value))\n\t\t\t})\n\t\t}\n\t}\n\n\tloadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})\n}\n","import {\n\tPluginArrayMethods,\n\tlatest,\n\tloadPlugin,\n\tmarkChanged,\n\tprepareCopy,\n\tProxyArrayState\n} from \"../internal\"\n\n/**\n * Methods that directly modify the array in place.\n * These operate on the copy without creating per-element proxies:\n * - `push`, `pop`: Add/remove from end\n * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)\n * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)\n * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)\n */\ntype MutatingArrayMethod =\n\t| \"push\"\n\t| \"pop\"\n\t| \"shift\"\n\t| \"unshift\"\n\t| \"splice\"\n\t| \"reverse\"\n\t| \"sort\"\n\n/**\n * Methods that read from the array without modifying it.\n * These fall into distinct categories based on return semantics:\n *\n * **Subset operations** (return drafts - mutations propagate):\n * - `filter`, `slice`: Return array of draft proxies\n * - `find`, `findLast`: Return single draft proxy or undefined\n *\n * **Transform operations** (return base values - mutations don't track):\n * - `concat`, `flat`: Create new structures, not subsets of original\n *\n * **Primitive-returning** (no draft needed):\n * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers\n * - `some`, `every`, `includes`: Return booleans\n * - `join`, `toString`, `toLocaleString`: Return strings\n */\ntype NonMutatingArrayMethod =\n\t| \"filter\"\n\t| \"slice\"\n\t| \"concat\"\n\t| \"flat\"\n\t| \"find\"\n\t| \"findIndex\"\n\t| \"findLast\"\n\t| \"findLastIndex\"\n\t| \"some\"\n\t| \"every\"\n\t| \"indexOf\"\n\t| \"lastIndexOf\"\n\t| \"includes\"\n\t| \"join\"\n\t| \"toString\"\n\t| \"toLocaleString\"\n\n/** Union of all array operation methods handled by the plugin. */\nexport type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod\n\n/**\n * Enables optimized array method handling for Immer drafts.\n *\n * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,\n * significantly improving performance for array-heavy operations.\n *\n * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):\n * Operate directly on the copy without creating per-element proxies.\n *\n * **Non-mutating methods** fall into categories:\n * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track\n * - **Transform operations** (concat, flat): Return base values - mutations don't track\n * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives\n *\n * **Important**: Callbacks for overridden methods receive base values, not drafts.\n * This is the core performance optimization.\n *\n * @example\n * ```ts\n * import { enableArrayMethods, produce } from \"immer\"\n *\n * enableArrayMethods()\n *\n * const next = produce(state, draft => {\n *   // Optimized - no proxy creation per element\n *   draft.items.sort((a, b) => a.value - b.value)\n *\n *   // filter returns drafts - mutations propagate\n *   const filtered = draft.items.filter(x => x.value > 5)\n *   filtered[0].value = 999 // Affects draft.items[originalIndex]\n * })\n * ```\n *\n * @see https://immerjs.github.io/immer/array-methods\n */\nexport function enableArrayMethods() {\n\tconst SHIFTING_METHODS = new Set<MutatingArrayMethod>([\"shift\", \"unshift\"])\n\n\tconst QUEUE_METHODS = new Set<MutatingArrayMethod>([\"push\", \"pop\"])\n\n\tconst RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...QUEUE_METHODS,\n\t\t...SHIFTING_METHODS\n\t])\n\n\tconst REORDERING_METHODS = new Set<MutatingArrayMethod>([\"reverse\", \"sort\"])\n\n\t// Optimized method detection using array-based lookup\n\tconst MUTATING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...RESULT_RETURNING_METHODS,\n\t\t...REORDERING_METHODS,\n\t\t\"splice\"\n\t])\n\n\tconst FIND_METHODS = new Set<NonMutatingArrayMethod>([\"find\", \"findLast\"])\n\n\tconst NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([\n\t\t\"filter\",\n\t\t\"slice\",\n\t\t\"concat\",\n\t\t\"flat\",\n\t\t...FIND_METHODS,\n\t\t\"findIndex\",\n\t\t\"findLastIndex\",\n\t\t\"some\",\n\t\t\"every\",\n\t\t\"indexOf\",\n\t\t\"lastIndexOf\",\n\t\t\"includes\",\n\t\t\"join\",\n\t\t\"toString\",\n\t\t\"toLocaleString\"\n\t])\n\n\t// Type guard for method detection\n\tfunction isMutatingArrayMethod(\n\t\tmethod: string\n\t): method is MutatingArrayMethod {\n\t\treturn MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isNonMutatingArrayMethod(\n\t\tmethod: string\n\t): method is NonMutatingArrayMethod {\n\t\treturn NON_MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isArrayOperationMethod(\n\t\tmethod: string\n\t): method is ArrayOperationMethod {\n\t\treturn isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)\n\t}\n\n\tfunction enterOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: ArrayOperationMethod\n\t) {\n\t\tstate.operationMethod = method\n\t}\n\n\tfunction exitOperation(state: ProxyArrayState) {\n\t\tstate.operationMethod = undefined\n\t}\n\n\t// Shared utility functions for array method handlers\n\tfunction executeArrayMethod<T>(\n\t\tstate: ProxyArrayState,\n\t\toperation: () => T,\n\t\tmarkLength = true\n\t): T {\n\t\tprepareCopy(state)\n\t\tconst result = operation()\n\t\tmarkChanged(state)\n\t\tif (markLength) state.assigned_!.set(\"length\", true)\n\t\treturn result\n\t}\n\n\tfunction markAllIndicesReassigned(state: ProxyArrayState) {\n\t\tstate.allIndicesReassigned_ = true\n\t}\n\n\tfunction normalizeSliceIndex(index: number, length: number): number {\n\t\tif (index < 0) {\n\t\t\treturn Math.max(length + index, 0)\n\t\t}\n\t\treturn Math.min(index, length)\n\t}\n\n\t/**\n\t * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).\n\t *\n\t * Operates directly on `state.copy_` without creating per-element proxies.\n\t * For shifting methods (shift, unshift), marks all indices as reassigned since\n\t * indices shift.\n\t *\n\t * @returns For push/pop/shift/unshift: the native method result. For others: the draft.\n\t */\n\tfunction handleSimpleOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(state, () => {\n\t\t\tconst result = (state.copy_! as any)[method](...args)\n\n\t\t\t// Handle index reassignment for shifting methods\n\t\t\tif (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t}\n\n\t\t\t// Return appropriate value based on method\n\t\t\treturn RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)\n\t\t\t\t? result\n\t\t\t\t: state.draft_\n\t\t})\n\t}\n\n\t/**\n\t * Handles reordering operations (reverse, sort) that change element order.\n\t *\n\t * Operates directly on `state.copy_` and marks all indices as reassigned\n\t * since element positions change. Does not mark length as changed since\n\t * these operations preserve array length.\n\t *\n\t * @returns The draft proxy for method chaining.\n\t */\n\tfunction handleReorderingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(\n\t\t\tstate,\n\t\t\t() => {\n\t\t\t\t;(state.copy_! as any)[method](...args)\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\treturn state.draft_\n\t\t\t},\n\t\t\tfalse\n\t\t) // Don't mark length as changed\n\t}\n\n\t/**\n\t * Creates an interceptor function for a specific array method.\n\t *\n\t * The interceptor wraps array method calls to:\n\t * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap\n\t *    to detect we're inside an optimized method and skip proxy creation)\n\t * 2. Route to appropriate handler based on method type\n\t * 3. Clean up the operation flag in `finally` block\n\t *\n\t * The `operationMethod` flag is the key mechanism that enables the proxy's `get`\n\t * trap to return base values instead of creating nested proxies during iteration.\n\t *\n\t * @param state - The proxy array state\n\t * @param originalMethod - Name of the array method being intercepted\n\t * @returns Interceptor function that handles the method call\n\t */\n\tfunction createMethodInterceptor(\n\t\tstate: ProxyArrayState,\n\t\toriginalMethod: string\n\t) {\n\t\treturn function interceptedMethod(...args: any[]) {\n\t\t\t// Enter operation mode - this flag tells the proxy's get trap to return\n\t\t\t// base values instead of creating nested proxies during iteration\n\t\t\tconst method = originalMethod as ArrayOperationMethod\n\t\t\tenterOperation(state, method)\n\n\t\t\ttry {\n\t\t\t\t// Check if this is a mutating method\n\t\t\t\tif (isMutatingArrayMethod(method)) {\n\t\t\t\t\t// Direct method dispatch - no configuration lookup needed\n\t\t\t\t\tif (RESULT_RETURNING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleSimpleOperation(state, method, args)\n\t\t\t\t\t}\n\t\t\t\t\tif (REORDERING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleReorderingOperation(state, method, args)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === \"splice\") {\n\t\t\t\t\t\tconst res = executeArrayMethod(state, () =>\n\t\t\t\t\t\t\tstate.copy_!.splice(...(args as [number, number, ...any[]]))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\t\t\treturn res\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle non-mutating methods\n\t\t\t\t\treturn handleNonMutatingOperation(state, method, args)\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// Always exit operation mode - must be in finally to handle exceptions\n\t\t\t\texitOperation(state)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Handles non-mutating array methods with different return semantics.\n\t *\n\t * **Subset operations** return draft proxies for mutation tracking:\n\t * - `filter`, `slice`: Return `state.draft_[i]` for each selected element\n\t * - `find`, `findLast`: Return `state.draft_[i]` for the found element\n\t *\n\t * This allows mutations on returned elements to propagate back to the draft:\n\t * ```ts\n\t * const filtered = draft.items.filter(x => x.value > 5)\n\t * filtered[0].value = 999 // Mutates draft.items[originalIndex]\n\t * ```\n\t *\n\t * **Transform operations** return base values (no draft tracking):\n\t * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.\n\t *   Since the result structure differs from the original, tracking mutations\n\t *   back to specific draft indices would be impractical/impossible.\n\t *\n\t * **Primitive operations** return the native result directly:\n\t * - `indexOf`, `includes`, `some`, `every`, `join`, etc.\n\t *\n\t * @param state - The proxy array state\n\t * @param method - The non-mutating method name\n\t * @param args - Arguments passed to the method\n\t * @returns Drafts for subset operations, base values for transforms, primitives otherwise\n\t */\n\tfunction handleNonMutatingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: NonMutatingArrayMethod,\n\t\targs: any[]\n\t) {\n\t\tconst source = latest(state)\n\n\t\t// Methods that return arrays with selected items - need to return drafts\n\t\tif (method === \"filter\") {\n\t\t\tconst predicate = args[0]\n\t\t\tconst result: any[] = []\n\n\t\t\t// First pass: call predicate on base values to determine which items pass\n\t\t\tfor (let i = 0; i < source.length; i++) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\t// Only create draft for items that passed the predicate\n\t\t\t\t\tresult.push(state.draft_[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\tif (FIND_METHODS.has(method)) {\n\t\t\tconst predicate = args[0]\n\t\t\tconst isForward = method === \"find\"\n\t\t\tconst step = isForward ? 1 : -1\n\t\t\tconst start = isForward ? 0 : source.length - 1\n\n\t\t\tfor (let i = start; i >= 0 && i < source.length; i += step) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\treturn state.draft_[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (method === \"slice\") {\n\t\t\tconst rawStart = args[0] ?? 0\n\t\t\tconst rawEnd = args[1] ?? source.length\n\n\t\t\t// Normalize negative indices\n\t\t\tconst start = normalizeSliceIndex(rawStart, source.length)\n\t\t\tconst end = normalizeSliceIndex(rawEnd, source.length)\n\n\t\t\tconst result: any[] = []\n\n\t\t\t// Return drafts for items in the slice range\n\t\t\tfor (let i = start; i < end; i++) {\n\t\t\t\tresult.push(state.draft_[i])\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\t// For other methods, call on base array directly:\n\t\t// - indexOf, includes, join, toString: Return primitives, no draft needed\n\t\t// - concat, flat: Return NEW arrays (not subsets). Elements are base values.\n\t\t//   This is intentional - concat/flat create new data structures rather than\n\t\t//   selecting subsets of the original, making draft tracking impractical.\n\t\treturn source[method as keyof typeof Array.prototype](...args)\n\t}\n\n\tloadPlugin(PluginArrayMethods, {\n\t\tcreateMethodInterceptor,\n\t\tisArrayOperationMethod,\n\t\tisMutatingArrayMethod\n\t})\n}\n","import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = /* @__PURE__ */ immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(\n\timmer\n)\n\n/**\n * Pass false to use loose iteration that only processes enumerable string properties.\n * This skips symbols and non-enumerable properties for maximum performance.\n *\n * By default, strict iteration is enabled (includes all own properties).\n */\nexport const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(\n\timmer\n)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = /* @__PURE__ */ immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport let castDraft = <T>(value: T): Draft<T> => value as any\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport let castImmutable = <T>(value: T): Immutable<T> => value as any\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableArrayMethods} from \"./plugins/arrayMethods\"\n"],"mappings":";AAKO,IAAM,UAAyB,OAAO,IAAI,eAAe;AAUzD,IAAM,YAA2B,OAAO,IAAI,iBAAiB;AAE7D,IAAM,cAA6B,OAAO,IAAI,aAAa;;;ACf3D,IAAM,SACZ,QAAQ,IAAI,aAAa,eACtB;AAAA;AAAA,EAEA,SAAS,QAAgB;AACxB,WAAO,mBAAmB,yFAAyF;AAAA,EACpH;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,sJAAsJ;AAAA,EAC9J;AAAA,EACA;AAAA,EACA,SAAS,MAAW;AACnB,WACC,yHACA;AAAA,EAEF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,mCAAmC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,OAAe;AACvB,WAAO,oCAAoC;AAAA,EAC5C;AAAA;AAAA;AAGA,IACA,CAAC;AAEE,SAAS,IAAI,UAAkB,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hE,IAAI,YAAY,CAAI,UAAuB;AAO3C,IAAI,gBAAgB,CAAI,UAA2B;","names":["immer","current","Immer","base","rootScope","isSet","current","set","Immer"]}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.production.mjs
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.production.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.production.mjs	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+var v=Symbol.for("immer-nothing"),B=Symbol.for("immer-draftable"),y=Symbol.for("immer-state");function b(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var C=Object,j=C.getPrototypeOf,ee="constructor",te="prototype",Se="configurable",ce="enumerable",se="writable",re="value",w=e=>!!e&&!!e[y];function _(e){return e?ze(e)||$(e)||!!e[B]||!!e[ee]?.[B]||q(e)||Y(e):!1}var $e=C[te][ee].toString(),Re=new WeakMap;function ze(e){if(!e||!H(e))return!1;let t=j(e);if(t===null||t===C[te])return!0;let r=C.hasOwnProperty.call(t,ee)&&t[ee];if(r===Object)return!0;if(!L(r))return!1;let n=Re.get(r);return n===void 0&&(n=Function.toString.call(r),Re.set(r,n)),n===$e}function qe(e){return w(e)||b(15,e),e[y].t}function U(e,t,r=!0){K(e)===0?(r?Reflect.ownKeys(e):C.keys(e)).forEach(o=>{t(o,e[o],e)}):e.forEach((n,o)=>t(o,n,e))}function K(e){let t=e[y];return t?t.r:$(e)?1:q(e)?2:Y(e)?3:0}var G=(e,t,r=K(e))=>r===2?e.has(t):C[te].hasOwnProperty.call(e,t),k=(e,t,r=K(e))=>r===2?e.get(t):e[t],ne=(e,t,r,n=K(e))=>{n===2?e.set(t,r):n===3?e.add(r):e[t]=r};function ke(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}var $=Array.isArray,q=e=>e instanceof Map,Y=e=>e instanceof Set,H=e=>typeof e=="object",L=e=>typeof e=="function",Pe=e=>typeof e=="boolean";function Ue(e){let t=+e;return Number.isInteger(t)&&String(t)===e}var De=e=>H(e)?e?.[y]:null,O=e=>e.e||e.t,je=e=>{let t=De(e);return t?t.e??t.t:e},ge=e=>e.s?e.e:e.t;function fe(e,t){if(q(e))return new Map(e);if(Y(e))return new Set(e);if($(e))return Array[te].slice.call(e);let r=ze(e);if(t===!0||t==="class_only"&&!r){let n=C.getOwnPropertyDescriptors(e);delete n[y];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let d=o[i],S=n[d];S[se]===!1&&(S[se]=!0,S[Se]=!0),(S.get||S.set)&&(n[d]={[Se]:!0,[se]:!0,[ce]:S[ce],[re]:e[d]})}return C.create(j(e),n)}else{let n=j(e);if(n!==null&&r)return{...e};let o=C.create(n);return C.assign(o,e)}}function ae(e,t=!1){return oe(e)||w(e)||!_(e)||(K(e)>1&&C.defineProperties(e,{set:me,add:me,clear:me,delete:me}),C.freeze(e),t&&U(e,(r,n)=>{ae(n,!0)},!1)),e}function Ye(){b(2)}var me={[re]:Ye};function oe(e){return e===null||!H(e)?!0:C.isFrozen(e)}var W="MapSet",J="Patches",le="ArrayMethods",xe={};function V(e){let t=xe[e];return t||b(0,e),t}var _e=e=>!!xe[e];function ie(e,t){xe[e]||(xe[e]=t)}var ye,Q=()=>ye,Je=(e,t)=>({o:[],i:e,l:t,F:!0,m:0,P:new Set,T:new Set,I:_e(W)?V(W):void 0,E:_e(le)?V(le):void 0});function Ee(e,t){t&&(e.x=V(J),e.p=[],e.d=[],e.C=t)}function de(e){Ae(e),e.o.forEach(Qe),e.o=null}function Ae(e){e===ye&&(ye=e.i)}var we=e=>ye=Je(ye,e);function Qe(e){let t=e[y];t.r===0||t.r===1?t.b():t.g=!0}function Fe(e,t){t.m=t.o.length;let r=t.o[0];if(e!==void 0&&e!==r){r[y].s&&(de(t),b(4)),_(e)&&(e=Le(t,e));let{x:o}=t;o&&o.M(r[y].t,e,t)}else e=Le(t,r);return Xe(t,e,!0),de(t),t.p&&t.C(t.p,t.d),e!==v?e:void 0}function Le(e,t){if(oe(t))return t;let r=t[y];if(!r)return Ie(t,e.P,e);if(!Me(r,e))return t;if(!r.s)return r.t;if(!r.u){let{f:n}=r;if(n)for(;n.length>0;)n.pop()(e);He(r,e)}return r.e}function Xe(e,t,r=!1){!e.i&&e.l.h&&e.F&&ae(t,r)}function Ve(e){e.u=!0,e.n.m--}var Me=(e,t)=>e.n===t,Ze=[];function Be(e,t,r,n){let o=O(e),i=e.r;if(n!==void 0&&k(o,n,i)===t){ne(o,n,r,i);return}if(!e.D){let S=e.D=new Map;U(o,(p,M)=>{if(w(M)){let a=S.get(M)||[];a.push(p),S.set(M,a)}})}let d=e.D.get(t)??Ze;for(let S of d)ne(o,S,r,i)}function Ke(e,t,r){e.f.push(function(o){let i=t;if(!i||!Me(i,o))return;o.I?.fixSetContents(i);let d=ge(i);Be(e,i.c??i,d,r),He(i,o)})}function He(e,t){if(e.s&&!e.u&&(e.r===3||e.r===1&&e.R||(e.a?.size??0)>0)){let{x:n}=t;if(n){let o=n.getPath(e);o&&n.O(e,o,t)}Ve(e)}}function pe(e,t,r){let{n}=e;if(w(r)){let o=r[y];Me(o,n)&&o.f.push(function(){X(e);let d=ge(o);Be(e,r,d,t)})}else _(r)&&e.f.push(function(){let i=O(e);e.r===3?i.has(r)&&Ie(r,n.P,n):k(i,t,e.r)===r&&n.o.length>1&&(e.a.get(t)??!1)===!0&&e.e&&Ie(k(e.e,t,e.r),n.P,n)})}function Ie(e,t,r){return!r.l.h&&r.m<1||w(e)||t.has(e)||!_(e)||oe(e)||(t.add(e),U(e,(n,o)=>{if(w(o)){let i=o[y];if(Me(i,r)){let d=ge(i);ne(e,n,d,e.r),Ve(i)}}else _(o)&&Ie(o,t,r)})),e}function We(e,t){let r=$(e),n={r:r?1:0,n:t?t.n:Q(),s:!1,u:!1,a:void 0,i:t,t:e,c:null,e:null,b:null,S:!1,f:void 0},o=n,i=Te;r&&(o=[n],i=he);let{revoke:d,proxy:S}=Proxy.revocable(o,i);return n.c=S,n.b=d,[S,n]}var Te={get(e,t){if(t===y)return e;let r=e.n.E,n=e.r===1&&typeof t=="string";if(n&&r?.isArrayOperationMethod(t))return r.createMethodInterceptor(e,t);let o=O(e);if(!G(o,t,e.r))return et(e,o,t);let i=o[t];if(e.u||!_(i)||n&&e.operationMethod&&r?.isMutatingArrayMethod(e.operationMethod)&&Ue(t))return i;if(i===Ce(e.t,t)){X(e);let d=e.r===1?+t:t,S=Z(e.n,i,e,d);return e.e[d]=S}return i},has(e,t){return t in O(e)},ownKeys(e){return Reflect.ownKeys(O(e))},set(e,t,r){let n=ve(O(e),t);if(n?.set)return n.set.call(e.c,r),!0;if(!e.s){let o=Ce(O(e),t),i=o?.[y];if(i&&i.t===r)return e.e[t]=r,e.a.set(t,!1),!0;if(ke(r,o)&&(r!==void 0||G(e.t,t,e.r)))return!0;X(e),z(e)}return e.e[t]===r&&(r!==void 0||t in e.e)||Number.isNaN(r)&&Number.isNaN(e.e[t])||(e.e[t]=r,e.a.set(t,!0),pe(e,t,r)),!0},deleteProperty(e,t){return X(e),Ce(e.t,t)!==void 0||t in e.t?(e.a.set(t,!1),z(e)):e.a.delete(t),e.e&&delete e.e[t],!0},getOwnPropertyDescriptor(e,t){let r=O(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{[se]:!0,[Se]:e.r!==1||t!=="length",[ce]:n[ce],[re]:r[t]}},defineProperty(){b(11)},getPrototypeOf(e){return j(e.t)},setPrototypeOf(){b(12)}},he={};for(let e in Te){let t=Te[e];he[e]=function(){let r=arguments;return r[0]=r[0][0],t.apply(this,r)}}he.deleteProperty=function(e,t){return he.set.call(this,e,t,void 0)};he.set=function(e,t,r){return Te.set.call(this,e[0],t,r,e[0])};function Ce(e,t){let r=e[y];return(r?O(r):e)[t]}function et(e,t,r){let n=ve(t,r);return n?re in n?n[re]:n.get?.call(e.c):void 0}function ve(e,t){if(!(t in e))return;let r=j(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=j(r)}}function z(e){e.s||(e.s=!0,e.i&&z(e.i))}function X(e){e.e||(e.a=new Map,e.e=fe(e.t,e.n.l.A))}var be=class{constructor(t){this.h=!0;this.A=!1;this._=!1;this.produce=(t,r,n)=>{if(L(t)&&!L(r)){let i=r;r=t;let d=this;return function(p=i,...M){return d.produce(p,a=>r.call(this,a,...M))}}L(r)||b(6),n!==void 0&&!L(n)&&b(7);let o;if(_(t)){let i=we(this),d=Z(i,t,void 0),S=!0;try{o=r(d),S=!1}finally{S?de(i):Ae(i)}return Ee(i,n),Fe(o,i)}else if(!t||!H(t)){if(o=r(t),o===void 0&&(o=t),o===v&&(o=void 0),this.h&&ae(o,!0),n){let i=[],d=[];V(J).M(t,o,{p:i,d}),n(i,d)}return o}else b(1,t)};this.produceWithPatches=(t,r)=>{if(L(t))return(d,...S)=>this.produceWithPatches(d,p=>t(p,...S));let n,o;return[this.produce(t,r,(d,S)=>{n=d,o=S}),n,o]};Pe(t?.autoFreeze)&&this.setAutoFreeze(t.autoFreeze),Pe(t?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),Pe(t?.useStrictIteration)&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){_(t)||b(8),w(t)&&(t=Ne(t));let r=we(this),n=Z(r,t,void 0);return n[y].S=!0,Ae(r),n}finishDraft(t,r){let n=t&&t[y];(!n||!n.S)&&b(9);let{n:o}=n;return Ee(o,r),Fe(void 0,o)}setAutoFreeze(t){this.h=t}setUseStrictShallowCopy(t){this.A=t}setUseStrictIteration(t){this._=t}shouldUseStrictIteration(){return this._}applyPatches(t,r){let n;for(n=r.length-1;n>=0;n--){let i=r[n];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}n>-1&&(r=r.slice(n+1));let o=V(J).N;return w(t)?o(t,r):this.produce(t,i=>o(i,r))}};function Z(e,t,r,n){let[o,i]=q(t)?V(W).w(t,r):Y(t)?V(W).V(t,r):We(t,r);return(r?.n??Q()).o.push(o),i.f=r?.f??[],i.y=n,r&&n!==void 0?Ke(r,i,n):i.f.push(function(p){p.I?.fixSetContents(i);let{x:M}=p;i.s&&M&&M.O(i,[],p)}),o}function Ne(e){return w(e)||b(10,e),Ge(e)}function Ge(e){if(!_(e)||oe(e))return e;let t=e[y],r,n=!0;if(t){if(!t.s)return t.t;t.u=!0,r=fe(e,t.n.l.A),n=t.n.l.shouldUseStrictIteration()}else r=fe(e,!0);return U(r,(o,i)=>{ne(r,o,Ge(i))},n),t&&(t.u=!1),r}function tt(){function t(u,g=[]){if(u.y!==void 0){let m=u.i.e??u.i.t,x=De(k(m,u.y)),A=k(m,u.y);if(A===void 0||A!==u.c&&A!==u.t&&A!==u.e||x!=null&&x.t!==u.t)return null;let s=u.i.r===3,l;if(s){let h=u.i;l=Array.from(h.o.keys()).indexOf(u.y)}else l=u.y;if(!(s&&m.size>l||G(m,l)))return null;g.push(l)}if(u.i)return t(u.i,g);g.reverse();try{r(u.e,g)}catch{return null}return g}function r(u,g){let m=u;for(let x=0;x<g.length-1;x++){let A=g[x];if(m=k(m,A),!H(m)||m===null)throw new Error(`Cannot resolve path at '${g.join("/")}'`)}return m}let n="replace",o="add",i="remove";function d(u,g,m){if(u.n.T.has(u))return;u.n.T.add(u);let{p:x,d:A}=m;switch(u.r){case 0:case 2:return p(u,g,x,A);case 1:return S(u,g,x,A);case 3:return M(u,g,x,A)}}function S(u,g,m,x){let{t:A,a:s}=u,l=u.e;l.length<A.length&&([A,l]=[l,A],[m,x]=[x,m]);let h=u.R===!0;for(let f=0;f<A.length;f++){let I=l[f],E=A[f];if((h||s?.get(f.toString()))&&I!==E){let N=I?.[y];if(N&&N.s)continue;let R=g.concat([f]);m.push({op:n,path:R,value:D(I)}),x.push({op:n,path:R,value:D(E)})}}for(let f=A.length;f<l.length;f++){let I=g.concat([f]);m.push({op:o,path:I,value:D(l[f])})}for(let f=l.length-1;A.length<=f;--f){let I=g.concat([f]);x.push({op:i,path:I})}}function p(u,g,m,x){let{t:A,e:s,r:l}=u;U(u.a,(h,f)=>{let I=k(A,h,l),E=k(s,h,l),T=f?G(A,h)?n:o:i;if(I===E&&T===n)return;let N=g.concat(h);m.push(T===i?{op:T,path:N}:{op:T,path:N,value:D(E)}),x.push(T===o?{op:i,path:N}:T===i?{op:o,path:N,value:D(I)}:{op:n,path:N,value:D(I)})})}function M(u,g,m,x){let{t:A,e:s}=u,l=0;A.forEach(h=>{if(!s.has(h)){let f=g.concat([l]);m.push({op:i,path:f,value:h}),x.unshift({op:o,path:f,value:h})}l++}),l=0,s.forEach(h=>{if(!A.has(h)){let f=g.concat([l]);m.push({op:o,path:f,value:h}),x.unshift({op:i,path:f,value:h})}l++})}function a(u,g,m){let{p:x,d:A}=m;x.push({op:n,path:[],value:g===v?void 0:g}),A.push({op:n,path:[],value:u})}function c(u,g){return g.forEach(m=>{let{path:x,op:A}=m,s=u;for(let I=0;I<x.length-1;I++){let E=K(s),T=x[I];typeof T!="string"&&typeof T!="number"&&(T=""+T),(E===0||E===1)&&(T==="__proto__"||T===ee)&&b(16+3),L(s)&&T===te&&b(16+3),s=k(s,T),H(s)||b(16+2,x.join("/"))}let l=K(s),h=P(m.value),f=x[x.length-1];switch(A){case n:switch(l){case 2:return s.set(f,h);case 3:b(16);default:return s[f]=h}case o:switch(l){case 1:return f==="-"?s.push(h):s.splice(f,0,h);case 2:return s.set(f,h);case 3:return s.add(h);default:return s[f]=h}case i:switch(l){case 1:return s.splice(f,1);case 2:return s.delete(f);case 3:return s.delete(m.value);default:return delete s[f]}default:b(16+1,A)}}),u}function P(u){if(!_(u))return u;if($(u))return u.map(P);if(q(u))return new Map(Array.from(u.entries()).map(([m,x])=>[m,P(x)]));if(Y(u))return new Set(Array.from(u).map(P));let g=Object.create(j(u));for(let m in u)g[m]=P(u[m]);return G(u,B)&&(g[B]=u[B]),g}function D(u){return w(u)?P(u):u}ie(J,{N:c,O:d,M:a,getPath:t})}function rt(){class e extends Map{constructor(a,c){super();this[y]={r:2,i:c,n:c?c.n:Q(),s:!1,u:!1,e:void 0,a:void 0,t:a,c:this,S:!1,g:!1,f:[]}}get size(){return O(this[y]).size}has(a){return O(this[y]).has(a)}set(a,c){let P=this[y];return d(P),(!O(P).has(a)||O(P).get(a)!==c)&&(r(P),z(P),P.a.set(a,!0),P.e.set(a,c),P.a.set(a,!0),pe(P,a,c)),this}delete(a){if(!this.has(a))return!1;let c=this[y];return d(c),r(c),z(c),c.t.has(a)?c.a.set(a,!1):c.a.delete(a),c.e.delete(a),!0}clear(){let a=this[y];d(a),O(a).size&&(r(a),z(a),a.a=new Map,U(a.t,c=>{a.a.set(c,!1)}),a.e.clear())}forEach(a,c){let P=this[y];O(P).forEach((D,u,g)=>{a.call(c,this.get(u),u,this)})}get(a){let c=this[y];d(c);let P=O(c).get(a);if(c.u||!_(P)||P!==c.t.get(a))return P;let D=Z(c.n,P,c,a);return r(c),c.e.set(a,D),D}keys(){return O(this[y]).keys()}values(){let a=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let c=a.next();return c.done?c:{done:!1,value:this.get(c.value)}}}}entries(){let a=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let c=a.next();if(c.done)return c;let P=this.get(c.value);return{done:!1,value:[c.value,P]}}}}[(y,Symbol.iterator)](){return this.entries()}}function t(p,M){let a=new e(p,M);return[a,a[y]]}function r(p){p.e||(p.a=new Map,p.e=new Map(p.t))}class n extends Set{constructor(a,c){super();this[y]={r:3,i:c,n:c?c.n:Q(),s:!1,u:!1,e:void 0,t:a,c:this,o:new Map,g:!1,S:!1,a:void 0,f:[]}}get size(){return O(this[y]).size}has(a){let c=this[y];return d(c),c.e?!!(c.e.has(a)||c.o.has(a)&&c.e.has(c.o.get(a))):c.t.has(a)}add(a){let c=this[y];return d(c),this.has(a)||(i(c),z(c),c.e.add(a),pe(c,a,a)),this}delete(a){if(!this.has(a))return!1;let c=this[y];return d(c),i(c),z(c),c.e.delete(a)||(c.o.has(a)?c.e.delete(c.o.get(a)):!1)}clear(){let a=this[y];d(a),O(a).size&&(i(a),z(a),a.e.clear())}values(){let a=this[y];return d(a),i(a),a.e.values()}entries(){let a=this[y];return d(a),i(a),a.e.entries()}keys(){return this.values()}[(y,Symbol.iterator)](){return this.values()}forEach(a,c){let P=this.values(),D=P.next();for(;!D.done;)a.call(c,D.value,D.value,this),D=P.next()}}function o(p,M){let a=new n(p,M);return[a,a[y]]}function i(p){p.e||(p.e=new Set,p.t.forEach(M=>{if(_(M)){let a=Z(p.n,M,p,M);p.o.set(M,a),p.e.add(a)}else p.e.add(M)}))}function d(p){p.g&&b(3,JSON.stringify(O(p)))}function S(p){if(p.r===3&&p.e){let M=new Set(p.e);p.e.clear(),M.forEach(a=>{p.e.add(je(a))})}}ie(W,{w:t,V:o,fixSetContents:S})}function nt(){let e=new Set(["shift","unshift"]),t=new Set(["push","pop"]),r=new Set([...t,...e]),n=new Set(["reverse","sort"]),o=new Set([...r,...n,"splice"]),i=new Set(["find","findLast"]),d=new Set(["filter","slice","concat","flat",...i,"findIndex","findLastIndex","some","every","indexOf","lastIndexOf","includes","join","toString","toLocaleString"]);function S(s){return o.has(s)}function p(s){return d.has(s)}function M(s){return S(s)||p(s)}function a(s,l){s.operationMethod=l}function c(s){s.operationMethod=void 0}function P(s,l,h=!0){X(s);let f=l();return z(s),h&&s.a.set("length",!0),f}function D(s){s.R=!0}function u(s,l){return s<0?Math.max(l+s,0):Math.min(s,l)}function g(s,l,h){return P(s,()=>{let f=s.e[l](...h);return e.has(l)&&D(s),r.has(l)?f:s.c})}function m(s,l,h){return P(s,()=>(s.e[l](...h),D(s),s.c),!1)}function x(s,l){return function(...f){let I=l;a(s,I);try{if(S(I)){if(r.has(I))return g(s,I,f);if(n.has(I))return m(s,I,f);if(I==="splice"){let E=P(s,()=>s.e.splice(...f));return D(s),E}}else return A(s,I,f)}finally{c(s)}}}function A(s,l,h){let f=O(s);if(l==="filter"){let I=h[0],E=[];for(let T=0;T<f.length;T++)I(f[T],T,f)&&E.push(s.c[T]);return E}if(i.has(l)){let I=h[0],E=l==="find",T=E?1:-1,N=E?0:f.length-1;for(let R=N;R>=0&&R<f.length;R+=T)if(I(f[R],R,f))return s.c[R];return}if(l==="slice"){let I=h[0]??0,E=h[1]??f.length,T=u(I,f.length),N=u(E,f.length),R=[];for(let Oe=T;Oe<N;Oe++)R.push(s.c[Oe]);return R}return f[l](...h)}ie(le,{createMethodInterceptor:x,isArrayOperationMethod:M,isMutatingArrayMethod:S})}var F=new be,vr=F.produce,Gr=F.produceWithPatches.bind(F),$r=F.setAutoFreeze.bind(F),qr=F.setUseStrictShallowCopy.bind(F),Yr=F.setUseStrictIteration.bind(F),Jr=F.applyPatches.bind(F),Qr=F.createDraft.bind(F),Xr=F.finishDraft.bind(F),Zr=e=>e,en=e=>e;export{be as Immer,Jr as applyPatches,Zr as castDraft,en as castImmutable,Qr as createDraft,Ne as current,nt as enableArrayMethods,rt as enableMapSet,tt as enablePatches,Xr as finishDraft,ae as freeze,B as immerable,w as isDraft,_ as isDraftable,v as nothing,qe as original,vr as produce,Gr as produceWithPatches,$r as setAutoFreeze,Yr as setUseStrictIteration,qr as setUseStrictShallowCopy};
+//# sourceMappingURL=immer.production.mjs.map
Index: node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.production.mjs.map
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.production.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/dist/immer.production.mjs.map	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+{"version":3,"sources":["../src/utils/env.ts","../src/utils/errors.ts","../src/utils/common.ts","../src/utils/plugins.ts","../src/core/scope.ts","../src/core/finalize.ts","../src/core/proxy.ts","../src/core/immerClass.ts","../src/core/current.ts","../src/plugins/patches.ts","../src/plugins/mapset.ts","../src/plugins/arrayMethods.ts","../src/immer.ts"],"sourcesContent":["// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","import {isFunction} from \"../internal\"\n\nexport const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t  ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = isFunction(e) ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nconst O = Object\n\nexport const getPrototypeOf = O.getPrototypeOf\n\nexport const CONSTRUCTOR = \"constructor\"\nexport const PROTOTYPE = \"prototype\"\n\nexport const CONFIGURABLE = \"configurable\"\nexport const ENUMERABLE = \"enumerable\"\nexport const WRITABLE = \"writable\"\nexport const VALUE = \"value\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tisArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value[CONSTRUCTOR]?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()\nconst cachedCtorStrings = new WeakMap()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || !isObjectish(value)) return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null || proto === O[PROTOTYPE]) return true\n\n\tconst Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]\n\tif (Ctor === Object) return true\n\n\tif (!isFunction(Ctor)) return false\n\n\tlet ctorString = cachedCtorStrings.get(Ctor)\n\tif (ctorString === undefined) {\n\t\tctorString = Function.toString.call(Ctor)\n\t\tcachedCtorStrings.set(Ctor, ctorString)\n\t}\n\n\treturn ctorString === objectCtorString\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n *\n * @param obj The object to iterate over\n * @param iter The iterator function\n * @param strict When true (default), includes symbols and non-enumerable properties.\n *               When false, uses looseiteration over only enumerable string properties.\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tstrict?: boolean\n): void\nexport function each(obj: any, iter: any, strict: boolean = true) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\t// If strict, we do a full iteration including symbols and non-enumerable properties\n\t\t// Otherwise, we only iterate enumerable string properties for performance\n\t\tconst keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)\n\t\tkeys.forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport let has = (\n\tthing: any,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): boolean =>\n\ttype === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: O[PROTOTYPE].hasOwnProperty.call(thing, prop)\n\n/*#__PURE__*/\nexport let get = (\n\tthing: AnyMap | AnyObject,\n\tprop: PropertyKey,\n\ttype = getArchtype(thing)\n): any =>\n\t// @ts-ignore\n\ttype === ArchType.Map ? thing.get(prop) : thing[prop]\n\n/*#__PURE__*/\nexport let set = (\n\tthing: any,\n\tpropOrOldValue: PropertyKey,\n\tvalue: any,\n\ttype = getArchtype(thing)\n) => {\n\tif (type === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (type === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\nexport let isArray = Array.isArray\n\n/*#__PURE__*/\nexport let isMap = (target: any): target is AnyMap => target instanceof Map\n\n/*#__PURE__*/\nexport let isSet = (target: any): target is AnySet => target instanceof Set\n\nexport let isObjectish = (target: any) => typeof target === \"object\"\n\nexport let isFunction = (target: any): target is Function =>\n\ttypeof target === \"function\"\n\nexport let isBoolean = (target: any): target is boolean =>\n\ttypeof target === \"boolean\"\n\nexport function isArrayIndex(value: string | number): value is number | string {\n\tconst n = +value\n\treturn Number.isInteger(n) && String(n) === value\n}\n\nexport let getProxyDraft = <T extends any>(value: T): ImmerState | null => {\n\tif (!isObjectish(value)) return null\n\treturn (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]\n}\n\n/*#__PURE__*/\nexport let latest = (state: ImmerState): any => state.copy_ || state.base_\n\nexport let getValue = <T extends object>(value: T): T => {\n\tconst proxyDraft = getProxyDraft(value)\n\treturn proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value\n}\n\nexport let getFinalValue = (state: ImmerState): any =>\n\tstate.modified_ ? state.copy_ : state.base_\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (isArray(base)) return Array[PROTOTYPE].slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = O.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc[WRITABLE] === false) {\n\t\t\t\tdesc[WRITABLE] = true\n\t\t\t\tdesc[CONFIGURABLE] = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\t[CONFIGURABLE]: true,\n\t\t\t\t\t[WRITABLE]: true, // could live with !!desc.set as well here...\n\t\t\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t\t\t[VALUE]: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn O.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = O.create(proto)\n\t\treturn O.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tO.defineProperties(obj, {\n\t\t\tset: dontMutateMethodOverride,\n\t\t\tadd: dontMutateMethodOverride,\n\t\t\tclear: dontMutateMethodOverride,\n\t\t\tdelete: dontMutateMethodOverride\n\t\t})\n\t}\n\tO.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.values (only string-like, enumerables) instead of each()\n\t\teach(\n\t\t\tobj,\n\t\t\t(_key, value) => {\n\t\t\t\tfreeze(value, true)\n\t\t\t},\n\t\t\tfalse\n\t\t)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nconst dontMutateMethodOverride = {\n\t[VALUE]: dontMutateFrozenCollections\n}\n\nexport function isFrozen(obj: any): boolean {\n\t// Fast path: primitives and null/undefined are always \"frozen\"\n\tif (obj === null || !isObjectish(obj)) return true\n\treturn O.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie,\n\tImmerScope,\n\tProxyArrayState\n} from \"../internal\"\n\nexport const PluginMapSet = \"MapSet\"\nexport const PluginPatches = \"Patches\"\nexport const PluginArrayMethods = \"ArrayMethods\"\n\nexport type PatchesPlugin = {\n\tgeneratePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\trootScope: ImmerScope\n\t): void\n\tgenerateReplacementPatches_(\n\t\tbase: any,\n\t\treplacement: any,\n\t\trootScope: ImmerScope\n\t): void\n\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\tgetPath: (state: ImmerState) => PatchPath | null\n}\n\nexport type MapSetPlugin = {\n\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]\n\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]\n\tfixSetContents: (state: ImmerState) => void\n}\n\nexport type ArrayMethodsPlugin = {\n\tcreateMethodInterceptor: (state: ProxyArrayState, method: string) => Function\n\tisArrayOperationMethod: (method: string) => boolean\n\tisMutatingArrayMethod: (method: string) => boolean\n}\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: PatchesPlugin\n\tMapSet?: MapSetPlugin\n\tArrayMethods?: ArrayMethodsPlugin\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>\n\t!!plugins[pluginKey]\n\nexport let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {\n\tdelete plugins[pluginKey]\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin,\n\tPatchesPlugin,\n\tMapSetPlugin,\n\tisPluginLoaded,\n\tPluginMapSet,\n\tPluginPatches,\n\tArrayMethodsPlugin,\n\tPluginArrayMethods\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tpatchPlugin_?: PatchesPlugin\n\tmapSetPlugin_?: MapSetPlugin\n\tarrayMethodsPlugin_?: ArrayMethodsPlugin\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n\thandledSet_: Set<any>\n\tprocessedForPatches_: Set<any>\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport let getCurrentScope = () => currentScope!\n\nlet createScope = (\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope => ({\n\tdrafts_: [],\n\tparent_,\n\timmer_,\n\t// Whenever the modified draft contains a draft from another scope, we\n\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\tcanAutoFreeze_: true,\n\tunfinalizedDrafts_: 0,\n\thandledSet_: new Set(),\n\tprocessedForPatches_: new Set(),\n\tmapSetPlugin_: isPluginLoaded(PluginMapSet)\n\t\t? getPlugin(PluginMapSet)\n\t\t: undefined,\n\tarrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods)\n\t\t? getPlugin(PluginArrayMethods)\n\t\t: undefined\n})\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tscope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport let enterScope = (immer: Immer) =>\n\t(currentScope = createScope(currentScope, immer))\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tget,\n\tPatch,\n\tlatest,\n\tprepareCopy,\n\tgetFinalValue,\n\tgetValue,\n\tProxyArrayState\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t}\n\t\tconst {patchPlugin_} = scope\n\t\tif (patchPlugin_) {\n\t\t\tpatchPlugin_.generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft)\n\t}\n\n\tmaybeFreeze(scope, result, true)\n\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\tif (!state) {\n\t\tconst finalValue = handleValue(value, rootScope.handledSet_, rootScope)\n\t\treturn finalValue\n\t}\n\n\t// Never finalize drafts owned by another scope\n\tif (!isSameScope(state, rootScope)) {\n\t\treturn value\n\t}\n\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\treturn state.base_\n\t}\n\n\tif (!state.finalized_) {\n\t\t// Execute all registered draft finalization callbacks\n\t\tconst {callbacks_} = state\n\t\tif (callbacks_) {\n\t\t\twhile (callbacks_.length > 0) {\n\t\t\t\tconst callback = callbacks_.pop()!\n\t\t\t\tcallback(rootScope)\n\t\t\t}\n\t\t}\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t}\n\n\t// By now the root copy has been fully updated throughout its tree\n\treturn state.copy_\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n\nfunction markStateFinalized(state: ImmerState) {\n\tstate.finalized_ = true\n\tstate.scope_.unfinalizedDrafts_--\n}\n\nlet isSameScope = (state: ImmerState, rootScope: ImmerScope) =>\n\tstate.scope_ === rootScope\n\n// A reusable empty array to avoid allocations\nconst EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []\n\n// Updates all references to a draft in its parent to the finalized value.\n// This handles cases where the same draft appears multiple times in the parent, or has been moved around.\nexport function updateDraftInParent(\n\tparent: ImmerState,\n\tdraftValue: any,\n\tfinalizedValue: any,\n\toriginalKey?: string | number | symbol\n): void {\n\tconst parentCopy = latest(parent)\n\tconst parentType = parent.type_\n\n\t// Fast path: Check if draft is still at original key\n\tif (originalKey !== undefined) {\n\t\tconst currentValue = get(parentCopy, originalKey, parentType)\n\t\tif (currentValue === draftValue) {\n\t\t\t// Still at original location, just update it\n\t\t\tset(parentCopy, originalKey, finalizedValue, parentType)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Slow path: Build reverse mapping of all children\n\t// to their indices in the parent, so that we can\n\t// replace all locations where this draft appears.\n\t// We only have to build this once per parent.\n\tif (!parent.draftLocations_) {\n\t\tconst draftLocations = (parent.draftLocations_ = new Map())\n\n\t\t// Use `each` which works on Arrays, Maps, and Objects\n\t\teach(parentCopy, (key, value) => {\n\t\t\tif (isDraft(value)) {\n\t\t\t\tconst keys = draftLocations.get(value) || []\n\t\t\t\tkeys.push(key)\n\t\t\t\tdraftLocations.set(value, keys)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Look up all locations where this draft appears\n\tconst locations =\n\t\tparent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT\n\n\t// Update all locations\n\tfor (const location of locations) {\n\t\tset(parentCopy, location, finalizedValue, parentType)\n\t}\n}\n\n// Register a callback to finalize a child draft when the parent draft is finalized.\n// This assumes there is a parent -> child relationship between the two drafts,\n// and we have a key to locate the child in the parent.\nexport function registerChildFinalizationCallback(\n\tparent: ImmerState,\n\tchild: ImmerState,\n\tkey: string | number | symbol\n) {\n\tparent.callbacks_.push(function childCleanup(rootScope) {\n\t\tconst state: ImmerState = child\n\n\t\t// Can only continue if this is a draft owned by this scope\n\t\tif (!state || !isSameScope(state, rootScope)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle potential set value finalization first\n\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t// Update all locations in the parent that referenced this draft\n\t\tupdateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)\n\n\t\tgeneratePatchesAndFinalize(state, rootScope)\n\t})\n}\n\nfunction generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {\n\tconst shouldFinalize =\n\t\tstate.modified_ &&\n\t\t!state.finalized_ &&\n\t\t(state.type_ === ArchType.Set ||\n\t\t\t(state.type_ === ArchType.Array &&\n\t\t\t\t(state as ProxyArrayState).allIndicesReassigned_) ||\n\t\t\t(state.assigned_?.size ?? 0) > 0)\n\n\tif (shouldFinalize) {\n\t\tconst {patchPlugin_} = rootScope\n\t\tif (patchPlugin_) {\n\t\t\tconst basePath = patchPlugin_!.getPath(state)\n\n\t\t\tif (basePath) {\n\t\t\t\tpatchPlugin_!.generatePatches_(state, basePath, rootScope)\n\t\t\t}\n\t\t}\n\n\t\tmarkStateFinalized(state)\n\t}\n}\n\nexport function handleCrossReference(\n\ttarget: ImmerState,\n\tkey: string | number | symbol,\n\tvalue: any\n) {\n\tconst {scope_} = target\n\t// Check if value is a draft from this scope\n\tif (isDraft(value)) {\n\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\tif (isSameScope(state, scope_)) {\n\t\t\t// Register callback to update this location when the draft finalizes\n\n\t\t\tstate.callbacks_.push(function crossReferenceCleanup() {\n\t\t\t\t// Update the target location with finalized value\n\t\t\t\tprepareCopy(target)\n\n\t\t\t\tconst finalizedValue = getFinalValue(state)\n\n\t\t\t\tupdateDraftInParent(target, value, finalizedValue, key)\n\t\t\t})\n\t\t}\n\t} else if (isDraftable(value)) {\n\t\t// Handle non-draft objects that might contain drafts\n\t\ttarget.callbacks_.push(function nestedDraftCleanup() {\n\t\t\tconst targetCopy = latest(target)\n\n\t\t\t// For Sets, check if value is still in the set\n\t\t\tif (target.type_ === ArchType.Set) {\n\t\t\t\tif (targetCopy.has(value)) {\n\t\t\t\t\t// Process the value to replace any nested drafts\n\t\t\t\t\thandleValue(value, scope_.handledSet_, scope_)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Maps/objects\n\t\t\t\tif (get(targetCopy, key, target.type_) === value) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tscope_.drafts_.length > 1 &&\n\t\t\t\t\t\t((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??\n\t\t\t\t\t\t\tfalse) === true &&\n\t\t\t\t\t\ttarget.copy_\n\t\t\t\t\t) {\n\t\t\t\t\t\t// This might be a non-draft value that has drafts\n\t\t\t\t\t\t// inside. We do need to recurse here to handle those.\n\t\t\t\t\t\thandleValue(\n\t\t\t\t\t\t\tget(target.copy_, key, target.type_),\n\t\t\t\t\t\t\tscope_.handledSet_,\n\t\t\t\t\t\t\tscope_\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nexport function handleValue(\n\ttarget: any,\n\thandledSet: Set<any>,\n\trootScope: ImmerScope\n) {\n\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t// This benefits especially adding large data tree's without further processing.\n\t\t// See add-data.js perf test\n\t\treturn target\n\t}\n\n\t// Skip if already handled, frozen, or not draftable\n\tif (\n\t\tisDraft(target) ||\n\t\thandledSet.has(target) ||\n\t\t!isDraftable(target) ||\n\t\tisFrozen(target)\n\t) {\n\t\treturn target\n\t}\n\n\thandledSet.add(target)\n\n\t// Process ALL properties/entries\n\teach(target, (key, value) => {\n\t\tif (isDraft(value)) {\n\t\t\tconst state: ImmerState = value[DRAFT_STATE]\n\t\t\tif (isSameScope(state, rootScope)) {\n\t\t\t\t// Replace draft with finalized value\n\n\t\t\t\tconst updatedValue = getFinalValue(state)\n\n\t\t\t\tset(target, key, updatedValue, target.type_)\n\n\t\t\t\tmarkStateFinalized(state)\n\t\t\t}\n\t\t} else if (isDraftable(value)) {\n\t\t\t// Recursively handle nested values\n\t\t\thandleValue(value, handledSet, rootScope)\n\t\t}\n\t})\n\n\treturn target\n}\n","import {\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\thandleCrossReference,\n\tWRITABLE,\n\tCONFIGURABLE,\n\tENUMERABLE,\n\tVALUE,\n\tisArray,\n\tisArrayIndex\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n\toperationMethod?: string\n\tallIndicesReassigned_?: boolean\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): [Drafted<T, ProxyState>, ProxyState] {\n\tconst baseIsArray = isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: baseIsArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\t// actually instantiated in `prepareCopy()`\n\t\tassigned_: undefined,\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false,\n\t\t// `callbacks` actually gets assigned in `createProxy`\n\t\tcallbacks_: undefined as any\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (baseIsArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn [proxy as any, state]\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tlet arrayPlugin = state.scope_.arrayMethodsPlugin_\n\t\tconst isArrayWithStringProp =\n\t\t\tstate.type_ === ArchType.Array && typeof prop === \"string\"\n\t\t// Intercept array methods so that we can override\n\t\t// behavior and skip proxy creation for perf\n\t\tif (isArrayWithStringProp) {\n\t\t\tif (arrayPlugin?.isArrayOperationMethod(prop)) {\n\t\t\t\treturn arrayPlugin.createMethodInterceptor(state, prop)\n\t\t\t}\n\t\t}\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop, state.type_)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\t// During mutating array operations, defer proxy creation for array elements\n\t\t// This optimization avoids creating unnecessary proxies during sort/reverse\n\t\tif (\n\t\t\tisArrayWithStringProp &&\n\t\t\t(state as ProxyArrayState).operationMethod &&\n\t\t\tarrayPlugin?.isMutatingArrayMethod(\n\t\t\t\t(state as ProxyArrayState).operationMethod!\n\t\t\t) &&\n\t\t\tisArrayIndex(prop)\n\t\t) {\n\t\t\t// Return raw value during mutating operations, create proxy only if modified\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\t// Ensure array keys are always numbers\n\t\t\tconst childKey = state.type_ === ArchType.Array ? +(prop as string) : prop\n\t\t\tconst childDraft = createProxy(state.scope_, value, state, childKey)\n\n\t\t\treturn (state.copy_![childKey] = childDraft)\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_!.set(prop, false)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (\n\t\t\t\tis(value, current) &&\n\t\t\t\t(value !== undefined || has(state.base_, prop, state.type_))\n\t\t\t)\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_!.set(prop, true)\n\n\t\thandleCrossReference(state, prop, value)\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\tprepareCopy(state)\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_!.set(prop, false)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tstate.assigned_!.delete(prop)\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\t[WRITABLE]: true,\n\t\t\t[CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\t[ENUMERABLE]: desc[ENUMERABLE],\n\t\t\t[VALUE]: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\n// Use `for..in` instead of `each` to work around a weird\n// prod test suite issue\nfor (let key in objectTraps) {\n\tlet fn = objectTraps[key as keyof typeof objectTraps] as Function\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\tconst args = arguments\n\t\targs[0] = args[0][0]\n\t\treturn fn.apply(this, args)\n\t}\n}\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? VALUE in desc\n\t\t\t? desc[VALUE]\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t  // prototype, we should invoke it with the draft as context!\n\t\t\t  desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: ImmerState) {\n\tif (!state.copy_) {\n\t\t// Actually create the `assigned_` map now that we\n\t\t// know this is a modified draft.\n\t\tstate.assigned_ = new Map()\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent,\n\tImmerScope,\n\tregisterChildFinalizationCallback,\n\tArchType,\n\tMapSetPlugin,\n\tAnyMap,\n\tAnySet,\n\tisObjectish,\n\tisFunction,\n\tisBoolean,\n\tPluginMapSet,\n\tPluginPatches\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\"\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\tuseStrictIteration_: boolean = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t\tuseStrictIteration?: boolean\n\t}) {\n\t\tif (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)\n\t\tif (isBoolean(config?.useStrictShallowCopy))\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t\tif (isBoolean(config?.useStrictIteration))\n\t\t\tthis.setUseStrictIteration(config!.useStrictIteration)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (isFunction(base) && !isFunction(recipe)) {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (!isFunction(recipe)) die(6)\n\t\tif (patchListener !== undefined && !isFunction(patchListener)) die(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(scope, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || !isObjectish(base)) {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n\t\t\t\t\tpatches_: p,\n\t\t\t\t\tinversePatches_: ip\n\t\t\t\t} as ImmerScope) // dummy scope\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (isFunction(base)) {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(scope, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\t/**\n\t * Pass false to use faster iteration that skips non-enumerable properties\n\t * but still handles symbols for compatibility.\n\t *\n\t * By default, strict iteration is enabled (includes all own properties).\n\t */\n\tsetUseStrictIteration(value: boolean) {\n\t\tthis.useStrictIteration_ = value\n\t}\n\n\tshouldUseStrictIteration(): boolean {\n\t\treturn this.useStrictIteration_\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(PluginPatches).applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\trootScope: ImmerScope,\n\tvalue: T,\n\tparent?: ImmerState,\n\tkey?: string | number | symbol\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\t// returning a tuple here lets us skip a proxy access\n\t// to DRAFT_STATE later\n\tconst [draft, state] = isMap(value)\n\t\t? getPlugin(PluginMapSet).proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(PluginMapSet).proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent?.scope_ ?? getCurrentScope()\n\tscope.drafts_.push(draft)\n\n\t// Ensure the parent callbacks are passed down so we actually\n\t// track all callbacks added throughout the tree\n\tstate.callbacks_ = parent?.callbacks_ ?? []\n\tstate.key_ = key\n\n\tif (parent && key !== undefined) {\n\t\tregisterChildFinalizationCallback(parent, state, key)\n\t} else {\n\t\t// It's a root draft, register it with the scope\n\t\tstate.callbacks_.push(function rootDraftCleanup(rootScope) {\n\t\t\trootScope.mapSetPlugin_?.fixSetContents(state)\n\n\t\t\tconst {patchPlugin_} = rootScope\n\n\t\t\tif (state.modified_ && patchPlugin_) {\n\t\t\t\tpatchPlugin_.generatePatches_(state, [], rootScope)\n\t\t\t}\n\t\t})\n\t}\n\n\treturn draft as any\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tlet strict = true // Default to strict for compatibility\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t\tstrict = state.scope_.immer_.shouldUseStrictIteration()\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(\n\t\tcopy,\n\t\t(key, childValue) => {\n\t\t\tset(copy, key, currentImpl(childValue))\n\t\t},\n\t\tstrict\n\t)\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors,\n\tDRAFT_STATE,\n\tgetProxyDraft,\n\tImmerScope,\n\tisObjectish,\n\tisFunction,\n\tCONSTRUCTOR,\n\tPluginPatches,\n\tisArray,\n\tPROTOTYPE\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tfunction getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {\n\t\t// Step 1: Check if state has a stored key\n\t\tif (state.key_ !== undefined) {\n\t\t\t// Step 2: Validate the key is still valid in parent\n\n\t\t\tconst parentCopy = state.parent_!.copy_ ?? state.parent_!.base_\n\t\t\tconst proxyDraft = getProxyDraft(get(parentCopy, state.key_!))\n\t\t\tconst valueAtKey = get(parentCopy, state.key_!)\n\n\t\t\tif (valueAtKey === undefined) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Check if the value at the key is still related to this draft\n\t\t\t// It should be either the draft itself, the base, or the copy\n\t\t\tif (\n\t\t\t\tvalueAtKey !== state.draft_ &&\n\t\t\t\tvalueAtKey !== state.base_ &&\n\t\t\t\tvalueAtKey !== state.copy_\n\t\t\t) {\n\t\t\t\treturn null // Value was replaced with something else\n\t\t\t}\n\t\t\tif (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n\t\t\t\treturn null // Different draft\n\t\t\t}\n\n\t\t\t// Step 3: Handle Set case specially\n\t\t\tconst isSet = state.parent_!.type_ === ArchType.Set\n\t\t\tlet key: string | number\n\n\t\t\tif (isSet) {\n\t\t\t\t// For Sets, find the index in the drafts_ map\n\t\t\t\tconst setParent = state.parent_ as SetState\n\t\t\t\tkey = Array.from(setParent.drafts_.keys()).indexOf(state.key_)\n\t\t\t} else {\n\t\t\t\tkey = state.key_ as string | number\n\t\t\t}\n\n\t\t\t// Step 4: Validate key still exists in parent\n\t\t\tif (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {\n\t\t\t\treturn null // Key deleted\n\t\t\t}\n\n\t\t\t// Step 5: Add key to path\n\t\t\tpath.push(key)\n\t\t}\n\n\t\t// Step 6: Recurse to parent if exists\n\t\tif (state.parent_) {\n\t\t\treturn getPath(state.parent_, path)\n\t\t}\n\n\t\t// Step 7: At root - reverse path and validate\n\t\tpath.reverse()\n\n\t\ttry {\n\t\t\t// Validate path can be resolved from ROOT\n\t\t\tresolvePath(state.copy_, path)\n\t\t} catch (e) {\n\t\t\treturn null // Path invalid\n\t\t}\n\n\t\treturn path\n\t}\n\n\t// NEW: Add resolvePath helper function\n\tfunction resolvePath(base: any, path: PatchPath): any {\n\t\tlet current = base\n\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\tconst key = path[i]\n\t\t\tcurrent = get(current, key)\n\t\t\tif (!isObjectish(current) || current === null) {\n\t\t\t\tthrow new Error(`Cannot resolve path at '${path.join(\"/\")}'`)\n\t\t\t}\n\t\t}\n\t\treturn current\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tscope: ImmerScope\n\t): void {\n\t\tif (state.scope_.processedForPatches_.has(state)) {\n\t\t\treturn\n\t\t}\n\n\t\tstate.scope_.processedForPatches_.add(state)\n\n\t\tconst {patches_, inversePatches_} = scope\n\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches_!,\n\t\t\t\t\tinversePatches_!\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\tconst allReassigned = state.allIndicesReassigned_ === true\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tconst copiedItem = copy_[i]\n\t\t\tconst baseItem = base_[i]\n\n\t\t\tconst isAssigned = allReassigned || assigned_?.get(i.toString())\n\t\t\tif (isAssigned && copiedItem !== baseItem) {\n\t\t\t\tconst childState = copiedItem?.[DRAFT_STATE]\n\t\t\t\tif (childState && childState.modified_) {\n\t\t\t\t\t// Skip - let the child generate its own patches\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copiedItem)\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(baseItem)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_, type_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key, type_)\n\t\t\tconst value = get(copy_!, key, type_)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(\n\t\t\t\top === REMOVE\n\t\t\t\t\t? {op, path}\n\t\t\t\t\t: {op, path, value: clonePatchValueIfNeeded(value)}\n\t\t\t)\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tscope: ImmerScope\n\t): void {\n\t\tconst {patches_, inversePatches_} = scope\n\t\tpatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches_!.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === CONSTRUCTOR)\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (!isObjectish(base)) die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(PluginPatches, {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_,\n\t\tgetPath\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach,\n\tgetValue,\n\tPluginMapSet,\n\thandleCrossReference\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\thandleCrossReference(state, key, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_, value, state, key)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, MapState] {\n\t\t// @ts-ignore\n\t\tconst map = new DraftMap(target, parent)\n\t\treturn [map as any, map[DRAFT_STATE]]\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tcallbacks_: []\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t\thandleCrossReference(state, value, value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(\n\t\ttarget: T,\n\t\tparent?: ImmerState\n\t): [T, SetState] {\n\t\t// @ts-ignore\n\t\tconst set = new DraftSet(target, parent)\n\t\treturn [set as any, set[DRAFT_STATE]]\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_, value, state, value)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tfunction fixSetContents(target: ImmerState) {\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\tif (target.type_ === ArchType.Set && target.copy_) {\n\t\t\tconst copy = new Set(target.copy_)\n\t\t\ttarget.copy_.clear()\n\t\t\tcopy.forEach(value => {\n\t\t\t\ttarget.copy_!.add(getValue(value))\n\t\t\t})\n\t\t}\n\t}\n\n\tloadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})\n}\n","import {\n\tPluginArrayMethods,\n\tlatest,\n\tloadPlugin,\n\tmarkChanged,\n\tprepareCopy,\n\tProxyArrayState\n} from \"../internal\"\n\n/**\n * Methods that directly modify the array in place.\n * These operate on the copy without creating per-element proxies:\n * - `push`, `pop`: Add/remove from end\n * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)\n * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)\n * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)\n */\ntype MutatingArrayMethod =\n\t| \"push\"\n\t| \"pop\"\n\t| \"shift\"\n\t| \"unshift\"\n\t| \"splice\"\n\t| \"reverse\"\n\t| \"sort\"\n\n/**\n * Methods that read from the array without modifying it.\n * These fall into distinct categories based on return semantics:\n *\n * **Subset operations** (return drafts - mutations propagate):\n * - `filter`, `slice`: Return array of draft proxies\n * - `find`, `findLast`: Return single draft proxy or undefined\n *\n * **Transform operations** (return base values - mutations don't track):\n * - `concat`, `flat`: Create new structures, not subsets of original\n *\n * **Primitive-returning** (no draft needed):\n * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers\n * - `some`, `every`, `includes`: Return booleans\n * - `join`, `toString`, `toLocaleString`: Return strings\n */\ntype NonMutatingArrayMethod =\n\t| \"filter\"\n\t| \"slice\"\n\t| \"concat\"\n\t| \"flat\"\n\t| \"find\"\n\t| \"findIndex\"\n\t| \"findLast\"\n\t| \"findLastIndex\"\n\t| \"some\"\n\t| \"every\"\n\t| \"indexOf\"\n\t| \"lastIndexOf\"\n\t| \"includes\"\n\t| \"join\"\n\t| \"toString\"\n\t| \"toLocaleString\"\n\n/** Union of all array operation methods handled by the plugin. */\nexport type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod\n\n/**\n * Enables optimized array method handling for Immer drafts.\n *\n * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,\n * significantly improving performance for array-heavy operations.\n *\n * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):\n * Operate directly on the copy without creating per-element proxies.\n *\n * **Non-mutating methods** fall into categories:\n * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track\n * - **Transform operations** (concat, flat): Return base values - mutations don't track\n * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives\n *\n * **Important**: Callbacks for overridden methods receive base values, not drafts.\n * This is the core performance optimization.\n *\n * @example\n * ```ts\n * import { enableArrayMethods, produce } from \"immer\"\n *\n * enableArrayMethods()\n *\n * const next = produce(state, draft => {\n *   // Optimized - no proxy creation per element\n *   draft.items.sort((a, b) => a.value - b.value)\n *\n *   // filter returns drafts - mutations propagate\n *   const filtered = draft.items.filter(x => x.value > 5)\n *   filtered[0].value = 999 // Affects draft.items[originalIndex]\n * })\n * ```\n *\n * @see https://immerjs.github.io/immer/array-methods\n */\nexport function enableArrayMethods() {\n\tconst SHIFTING_METHODS = new Set<MutatingArrayMethod>([\"shift\", \"unshift\"])\n\n\tconst QUEUE_METHODS = new Set<MutatingArrayMethod>([\"push\", \"pop\"])\n\n\tconst RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...QUEUE_METHODS,\n\t\t...SHIFTING_METHODS\n\t])\n\n\tconst REORDERING_METHODS = new Set<MutatingArrayMethod>([\"reverse\", \"sort\"])\n\n\t// Optimized method detection using array-based lookup\n\tconst MUTATING_METHODS = new Set<MutatingArrayMethod>([\n\t\t...RESULT_RETURNING_METHODS,\n\t\t...REORDERING_METHODS,\n\t\t\"splice\"\n\t])\n\n\tconst FIND_METHODS = new Set<NonMutatingArrayMethod>([\"find\", \"findLast\"])\n\n\tconst NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([\n\t\t\"filter\",\n\t\t\"slice\",\n\t\t\"concat\",\n\t\t\"flat\",\n\t\t...FIND_METHODS,\n\t\t\"findIndex\",\n\t\t\"findLastIndex\",\n\t\t\"some\",\n\t\t\"every\",\n\t\t\"indexOf\",\n\t\t\"lastIndexOf\",\n\t\t\"includes\",\n\t\t\"join\",\n\t\t\"toString\",\n\t\t\"toLocaleString\"\n\t])\n\n\t// Type guard for method detection\n\tfunction isMutatingArrayMethod(\n\t\tmethod: string\n\t): method is MutatingArrayMethod {\n\t\treturn MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isNonMutatingArrayMethod(\n\t\tmethod: string\n\t): method is NonMutatingArrayMethod {\n\t\treturn NON_MUTATING_METHODS.has(method as any)\n\t}\n\n\tfunction isArrayOperationMethod(\n\t\tmethod: string\n\t): method is ArrayOperationMethod {\n\t\treturn isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)\n\t}\n\n\tfunction enterOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: ArrayOperationMethod\n\t) {\n\t\tstate.operationMethod = method\n\t}\n\n\tfunction exitOperation(state: ProxyArrayState) {\n\t\tstate.operationMethod = undefined\n\t}\n\n\t// Shared utility functions for array method handlers\n\tfunction executeArrayMethod<T>(\n\t\tstate: ProxyArrayState,\n\t\toperation: () => T,\n\t\tmarkLength = true\n\t): T {\n\t\tprepareCopy(state)\n\t\tconst result = operation()\n\t\tmarkChanged(state)\n\t\tif (markLength) state.assigned_!.set(\"length\", true)\n\t\treturn result\n\t}\n\n\tfunction markAllIndicesReassigned(state: ProxyArrayState) {\n\t\tstate.allIndicesReassigned_ = true\n\t}\n\n\tfunction normalizeSliceIndex(index: number, length: number): number {\n\t\tif (index < 0) {\n\t\t\treturn Math.max(length + index, 0)\n\t\t}\n\t\treturn Math.min(index, length)\n\t}\n\n\t/**\n\t * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).\n\t *\n\t * Operates directly on `state.copy_` without creating per-element proxies.\n\t * For shifting methods (shift, unshift), marks all indices as reassigned since\n\t * indices shift.\n\t *\n\t * @returns For push/pop/shift/unshift: the native method result. For others: the draft.\n\t */\n\tfunction handleSimpleOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(state, () => {\n\t\t\tconst result = (state.copy_! as any)[method](...args)\n\n\t\t\t// Handle index reassignment for shifting methods\n\t\t\tif (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t}\n\n\t\t\t// Return appropriate value based on method\n\t\t\treturn RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)\n\t\t\t\t? result\n\t\t\t\t: state.draft_\n\t\t})\n\t}\n\n\t/**\n\t * Handles reordering operations (reverse, sort) that change element order.\n\t *\n\t * Operates directly on `state.copy_` and marks all indices as reassigned\n\t * since element positions change. Does not mark length as changed since\n\t * these operations preserve array length.\n\t *\n\t * @returns The draft proxy for method chaining.\n\t */\n\tfunction handleReorderingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: string,\n\t\targs: any[]\n\t) {\n\t\treturn executeArrayMethod(\n\t\t\tstate,\n\t\t\t() => {\n\t\t\t\t;(state.copy_! as any)[method](...args)\n\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\treturn state.draft_\n\t\t\t},\n\t\t\tfalse\n\t\t) // Don't mark length as changed\n\t}\n\n\t/**\n\t * Creates an interceptor function for a specific array method.\n\t *\n\t * The interceptor wraps array method calls to:\n\t * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap\n\t *    to detect we're inside an optimized method and skip proxy creation)\n\t * 2. Route to appropriate handler based on method type\n\t * 3. Clean up the operation flag in `finally` block\n\t *\n\t * The `operationMethod` flag is the key mechanism that enables the proxy's `get`\n\t * trap to return base values instead of creating nested proxies during iteration.\n\t *\n\t * @param state - The proxy array state\n\t * @param originalMethod - Name of the array method being intercepted\n\t * @returns Interceptor function that handles the method call\n\t */\n\tfunction createMethodInterceptor(\n\t\tstate: ProxyArrayState,\n\t\toriginalMethod: string\n\t) {\n\t\treturn function interceptedMethod(...args: any[]) {\n\t\t\t// Enter operation mode - this flag tells the proxy's get trap to return\n\t\t\t// base values instead of creating nested proxies during iteration\n\t\t\tconst method = originalMethod as ArrayOperationMethod\n\t\t\tenterOperation(state, method)\n\n\t\t\ttry {\n\t\t\t\t// Check if this is a mutating method\n\t\t\t\tif (isMutatingArrayMethod(method)) {\n\t\t\t\t\t// Direct method dispatch - no configuration lookup needed\n\t\t\t\t\tif (RESULT_RETURNING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleSimpleOperation(state, method, args)\n\t\t\t\t\t}\n\t\t\t\t\tif (REORDERING_METHODS.has(method)) {\n\t\t\t\t\t\treturn handleReorderingOperation(state, method, args)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === \"splice\") {\n\t\t\t\t\t\tconst res = executeArrayMethod(state, () =>\n\t\t\t\t\t\t\tstate.copy_!.splice(...(args as [number, number, ...any[]]))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tmarkAllIndicesReassigned(state)\n\t\t\t\t\t\treturn res\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Handle non-mutating methods\n\t\t\t\t\treturn handleNonMutatingOperation(state, method, args)\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// Always exit operation mode - must be in finally to handle exceptions\n\t\t\t\texitOperation(state)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Handles non-mutating array methods with different return semantics.\n\t *\n\t * **Subset operations** return draft proxies for mutation tracking:\n\t * - `filter`, `slice`: Return `state.draft_[i]` for each selected element\n\t * - `find`, `findLast`: Return `state.draft_[i]` for the found element\n\t *\n\t * This allows mutations on returned elements to propagate back to the draft:\n\t * ```ts\n\t * const filtered = draft.items.filter(x => x.value > 5)\n\t * filtered[0].value = 999 // Mutates draft.items[originalIndex]\n\t * ```\n\t *\n\t * **Transform operations** return base values (no draft tracking):\n\t * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.\n\t *   Since the result structure differs from the original, tracking mutations\n\t *   back to specific draft indices would be impractical/impossible.\n\t *\n\t * **Primitive operations** return the native result directly:\n\t * - `indexOf`, `includes`, `some`, `every`, `join`, etc.\n\t *\n\t * @param state - The proxy array state\n\t * @param method - The non-mutating method name\n\t * @param args - Arguments passed to the method\n\t * @returns Drafts for subset operations, base values for transforms, primitives otherwise\n\t */\n\tfunction handleNonMutatingOperation(\n\t\tstate: ProxyArrayState,\n\t\tmethod: NonMutatingArrayMethod,\n\t\targs: any[]\n\t) {\n\t\tconst source = latest(state)\n\n\t\t// Methods that return arrays with selected items - need to return drafts\n\t\tif (method === \"filter\") {\n\t\t\tconst predicate = args[0]\n\t\t\tconst result: any[] = []\n\n\t\t\t// First pass: call predicate on base values to determine which items pass\n\t\t\tfor (let i = 0; i < source.length; i++) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\t// Only create draft for items that passed the predicate\n\t\t\t\t\tresult.push(state.draft_[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\tif (FIND_METHODS.has(method)) {\n\t\t\tconst predicate = args[0]\n\t\t\tconst isForward = method === \"find\"\n\t\t\tconst step = isForward ? 1 : -1\n\t\t\tconst start = isForward ? 0 : source.length - 1\n\n\t\t\tfor (let i = start; i >= 0 && i < source.length; i += step) {\n\t\t\t\tif (predicate(source[i], i, source)) {\n\t\t\t\t\treturn state.draft_[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (method === \"slice\") {\n\t\t\tconst rawStart = args[0] ?? 0\n\t\t\tconst rawEnd = args[1] ?? source.length\n\n\t\t\t// Normalize negative indices\n\t\t\tconst start = normalizeSliceIndex(rawStart, source.length)\n\t\t\tconst end = normalizeSliceIndex(rawEnd, source.length)\n\n\t\t\tconst result: any[] = []\n\n\t\t\t// Return drafts for items in the slice range\n\t\t\tfor (let i = start; i < end; i++) {\n\t\t\t\tresult.push(state.draft_[i])\n\t\t\t}\n\n\t\t\treturn result\n\t\t}\n\n\t\t// For other methods, call on base array directly:\n\t\t// - indexOf, includes, join, toString: Return primitives, no draft needed\n\t\t// - concat, flat: Return NEW arrays (not subsets). Elements are base values.\n\t\t//   This is intentional - concat/flat create new data structures rather than\n\t\t//   selecting subsets of the original, making draft tracking impractical.\n\t\treturn source[method as keyof typeof Array.prototype](...args)\n\t}\n\n\tloadPlugin(PluginArrayMethods, {\n\t\tcreateMethodInterceptor,\n\t\tisArrayOperationMethod,\n\t\tisMutatingArrayMethod\n\t})\n}\n","import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = /* @__PURE__ */ immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(\n\timmer\n)\n\n/**\n * Pass false to use loose iteration that only processes enumerable string properties.\n * This skips symbols and non-enumerable properties for maximum performance.\n *\n * By default, strict iteration is enabled (includes all own properties).\n */\nexport const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(\n\timmer\n)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = /* @__PURE__ */ immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport let castDraft = <T>(value: T): Draft<T> => value as any\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport let castImmutable = <T>(value: T): Immutable<T> => value as any\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableArrayMethods} from \"./plugins/arrayMethods\"\n"],"mappings":"AAKO,IAAMA,EAAyB,OAAO,IAAI,eAAe,EAUnDC,EAA2B,OAAO,IAAI,iBAAiB,EAEvDC,EAA6B,OAAO,IAAI,aAAa,ECuB3D,SAASC,EAAIC,KAAkBC,EAAoB,CAMzD,MAAM,IAAI,MACT,8BAA8BD,0CAC/B,CACD,CCnCA,IAAME,EAAI,OAEGC,EAAiBD,EAAE,eAEnBE,GAAc,cACdC,GAAY,YAEZC,GAAe,eACfC,GAAa,aACbC,GAAW,WACXC,GAAQ,QAIVC,EAAWC,GAAwB,CAAC,CAACA,GAAS,CAAC,CAACA,EAAMC,CAAW,EAIrE,SAASC,EAAYF,EAAqB,CAChD,OAAKA,EAEJG,GAAcH,CAAK,GACnBI,EAAQJ,CAAK,GACb,CAAC,CAACA,EAAMK,CAAS,GACjB,CAAC,CAACL,EAAMP,EAAW,IAAIY,CAAS,GAChCC,EAAMN,CAAK,GACXO,EAAMP,CAAK,EAPO,EASpB,CAEA,IAAMQ,GAAmBjB,EAAEG,EAAS,EAAED,EAAW,EAAE,SAAS,EACtDgB,GAAoB,IAAI,QAEvB,SAASN,GAAcH,EAAqB,CAClD,GAAI,CAACA,GAAS,CAACU,EAAYV,CAAK,EAAG,MAAO,GAC1C,IAAMW,EAAQnB,EAAeQ,CAAK,EAClC,GAAIW,IAAU,MAAQA,IAAUpB,EAAEG,EAAS,EAAG,MAAO,GAErD,IAAMkB,EAAOrB,EAAE,eAAe,KAAKoB,EAAOlB,EAAW,GAAKkB,EAAMlB,EAAW,EAC3E,GAAImB,IAAS,OAAQ,MAAO,GAE5B,GAAI,CAACC,EAAWD,CAAI,EAAG,MA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AkB,GAAWC,GAAoB,CAC9B,wBAAAf,EACA,uBAAArB,EACA,sBAAAH,CACD,CAAC,CACF,CChXA,IAAMwC,EAAQ,IAAIC,GAqBLC,GAAoCF,EAAM,QAM1CG,GAA0DH,EAAM,mBAAmB,KAC/FA,CACD,EAOaI,GAAgCJ,EAAM,cAAc,KAAKA,CAAK,EAO9DK,GAA0CL,EAAM,wBAAwB,KACpFA,CACD,EAQaM,GAAwCN,EAAM,sBAAsB,KAChFA,CACD,EAOaO,GAA+BP,EAAM,aAAa,KAAKA,CAAK,EAM5DQ,GAA8BR,EAAM,YAAY,KAAKA,CAAK,EAU1DS,GAA8BT,EAAM,YAAY,KAAKA,CAAK,EAQ5DU,GAAgBC,GAAuBA,EAOvCC,GAAoBD,GAA2BA","names":["NOTHING","DRAFTABLE","DRAFT_STATE","die","error","args","O","getPrototypeOf","CONSTRUCTOR","PROTOTYPE","CONFIGURABLE","ENUMERABLE","WRITABLE","VALUE","isDraft","value","DRAFT_STATE","isDraftable","isPlainObject","isArray","DRAFTABLE","isMap","isSet","objectCtorString","cachedCtorStrings","isObjectish","proto","Ctor","isFunction","ctorString","original","die","base_","each","obj","iter","strict","getArchtype","key","entry","index","thing","state","type_","has","prop","type","get","set","propOrOldValue","is","x","y","target","isBoolean","isArrayIndex","n","getProxyDraft","latest","copy_","getValue","proxyDraft","getFinalValue","modified_","shallowCopy","base","isPlain","descriptors","keys","desc","freeze","deep","isFrozen","dontMutateMethodOverride","_key","dontMutateFrozenCollections","PluginMapSet","PluginPatches","PluginArrayMethods","plugins","getPlugin","pluginKey","plugin","die","isPluginLoaded","loadPlugin","pluginKey","implementation","plugins","currentScope","getCurrentScope","createScope","parent_","immer_","drafts_","canAutoFreeze_","unfinalizedDrafts_","handledSet_","processedForPatches_","mapSetPlugin_","isPluginLoaded","PluginMapSet","getPlugin","arrayMethodsPlugin_","PluginArrayMethods","usePatchesInScope","scope","patchListener","patchPlugin_","PluginPatches","patches_","inversePatches_","patchListener_","revokeScope","leaveScope","revokeDraft","enterScope","immer","draft","state","DRAFT_STATE","type_","revoke_","revoked_","processResult","result","scope","unfinalizedDrafts_","drafts_","baseDraft","DRAFT_STATE","modified_","revokeScope","die","isDraftable","finalize","patchPlugin_","generateReplacementPatches_","base_","maybeFreeze","patches_","patchListener_","inversePatches_","NOTHING","rootScope","value","isFrozen","state","handleValue","handledSet_","isSameScope","finalized_","callbacks_","generatePatchesAndFinalize","copy_","deep","parent_","immer_","autoFreeze_","canAutoFreeze_","freeze","markStateFinalized","scope_","EMPTY_LOCATIONS_RESULT","updateDraftInParent","parent","draftValue","finalizedValue","originalKey","parentCopy","latest","parentType","type_","get","set","draftLocations_","draftLocations","each","key","isDraft","keys","locations","location","registerChildFinalizationCallback","child","mapSetPlugin_","getFinalValue","draft_","allIndicesReassigned_","assigned_","basePath","generatePatches_","handleCrossReference","target","prepareCopy","targetCopy","handledSet","updatedValue","createProxyProxy","base","parent","baseIsArray","isArray","state","type_","scope_","getCurrentScope","modified_","finalized_","assigned_","parent_","base_","draft_","copy_","revoke_","isManual_","callbacks_","target","traps","objectTraps","arrayTraps","revoke","proxy","prop","DRAFT_STATE","arrayPlugin","arrayMethodsPlugin_","isArrayWithStringProp","source","latest","has","readPropFromProto","value","isDraftable","isArrayIndex","peek","prepareCopy","childKey","childDraft","createProxy","desc","getDescriptorFromProto","current","currentState","is","markChanged","handleCrossReference","owner","WRITABLE","CONFIGURABLE","ENUMERABLE","VALUE","die","getPrototypeOf","key","fn","args","draft","proto","shallowCopy","immer_","useStrictShallowCopy_","Immer","config","autoFreeze_","useStrictShallowCopy_","useStrictIteration_","base","recipe","patchListener","isFunction","defaultBase","self","args","draft","die","result","isDraftable","scope","enterScope","proxy","createProxy","hasError","revokeScope","leaveScope","usePatchesInScope","processResult","isObjectish","NOTHING","freeze","p","ip","getPlugin","PluginPatches","generateReplacementPatches_","patches_","inversePatches_","state","patches","inversePatches","isBoolean","isDraft","current","DRAFT_STATE","isManual_","scope_","value","i","patch","applyPatchesImpl","applyPatches_","rootScope","parent","key","isMap","PluginMapSet","proxyMap_","isSet","proxySet_","createProxyProxy","getCurrentScope","drafts_","callbacks_","key_","registerChildFinalizationCallback","mapSetPlugin_","patchPlugin_","modified_","generatePatches_","current","value","isDraft","die","currentImpl","isDraftable","isFrozen","state","DRAFT_STATE","copy","strict","modified_","base_","finalized_","shallowCopy","scope_","immer_","useStrictShallowCopy_","each","key","childValue","set","enablePatches","getPath","state","path","key_","parentCopy","parent_","copy_","base_","proxyDraft","getProxyDraft","get","valueAtKey","draft_","isSet","type_","key","setParent","drafts_","has","resolvePath","base","current","i","isObjectish","REPLACE","ADD","REMOVE","generatePatches_","basePath","scope","scope_","processedForPatches_","patches_","inversePatches_","generatePatchesFromAssigned","generateArrayPatches","generateSetPatches","patches","inversePatches","assigned_","allReassigned","allIndicesReassigned_","copiedItem","baseItem","childState","DRAFT_STATE","modified_","clonePatchValueIfNeeded","each","assignedValue","origValue","value","op","generateReplacementPatches_","baseValue","replacement","NOTHING","applyPatches_","draft","patch","parentType","getArchtype","p","CONSTRUCTOR","die","isFunction","PROTOTYPE","type","deepClonePatchValue","obj","isDraftable","isArray","isMap","k","v","cloned","getPrototypeOf","DRAFTABLE","isDraft","loadPlugin","PluginPatches","enableMapSet","DraftMap","target","parent","DRAFT_STATE","type_","parent_","scope_","getCurrentScope","modified_","finalized_","copy_","assigned_","base_","draft_","isManual_","revoked_","callbacks_","latest","key","value","state","assertUnrevoked","prepareMapCopy","markChanged","handleCrossReference","each","cb","thisArg","_value","_map","isDraftable","draft","createProxy","iterator","r","proxyMap_","map","DraftSet","drafts_","prepareSetCopy","result","proxySet_","set","die","fixSetContents","copy","getValue","loadPlugin","PluginMapSet","enableArrayMethods","SHIFTING_METHODS","QUEUE_METHODS","RESULT_RETURNING_METHODS","REORDERING_METHODS","MUTATING_METHODS","FIND_METHODS","NON_MUTATING_METHODS","isMutatingArrayMethod","method","isNonMutatingArrayMethod","isArrayOperationMethod","enterOperation","state","exitOperation","executeArrayMethod","operation","markLength","prepareCopy","result","markChanged","assigned_","markAllIndicesReassigned","allIndicesReassigned_","normalizeSliceIndex","index","length","handleSimpleOperation","args","copy_","draft_","handleReorderingOperation","createMethodInterceptor","originalMethod","res","handleNonMutatingOperation","source","latest","predicate","i","isForward","step","start","rawStart","rawEnd","end","loadPlugin","PluginArrayMethods","immer","Immer","produce","produceWithPatches","setAutoFreeze","setUseStrictShallowCopy","setUseStrictIteration","applyPatches","createDraft","finishDraft","castDraft","value","castImmutable"]}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/package.json
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,97 @@
+{
+  "name": "immer",
+  "version": "11.1.3",
+  "description": "Create your next immutable state by mutating the current one",
+  "main": "./dist/cjs/index.js",
+  "module": "./dist/immer.legacy-esm.js",
+  "exports": {
+    "./package.json": "./package.json",
+    ".": {
+      "react-native": {
+        "types": "./dist/immer.d.ts",
+        "default": "./dist/immer.legacy-esm.js"
+      },
+      "import": {
+        "types": "./dist/immer.d.ts",
+        "default": "./dist/immer.mjs"
+      },
+      "require": {
+        "types": "./dist/immer.d.ts",
+        "default": "./dist/cjs/index.js"
+      }
+    }
+  },
+  "jsnext:main": "dist/immer.mjs",
+  "source": "src/immer.ts",
+  "types": "./dist/immer.d.ts",
+  "sideEffects": false,
+  "scripts": {
+    "test": "vitest run && yarn test:build && yarn test:flow",
+    "test:perf": "cd __performance_tests__ && node add-data.mjs && node todo.mjs && node incremental.mjs && node large-obj.mjs",
+    "test:flow": "yarn flow check __tests__/flow",
+    "test:build": "yarn build && vitest run --config vitest.config.build.ts",
+    "test:src": "vitest run",
+    "watch": "vitest",
+    "coverage": "vitest run --coverage",
+    "coveralls": "vitest run --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",
+    "build": "tsup",
+    "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn docusaurus deploy",
+    "start": "cd website && yarn start",
+    "test:size": "yarn build && yarn import-size --report . produce enableMapSet enablePatches enableArrayMethods",
+    "test:sizequick": "yarn build && yarn import-size . produce"
+  },
+  "husky": {
+    "hooks": {
+      "pre-commit": "pretty-quick --staged"
+    }
+  },
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/immerjs/immer.git"
+  },
+  "keywords": [
+    "immutable",
+    "mutable",
+    "copy-on-write"
+  ],
+  "author": "Michel Weststrate <info@michel.codes>",
+  "license": "MIT",
+  "funding": {
+    "type": "opencollective",
+    "url": "https://opencollective.com/immer"
+  },
+  "bugs": {
+    "url": "https://github.com/immerjs/immer/issues"
+  },
+  "homepage": "https://github.com/immerjs/immer#readme",
+  "files": [
+    "dist",
+    "compat",
+    "src"
+  ],
+  "devDependencies": {
+    "@babel/core": "^7.21.3",
+    "@types/node": "^24.3.1",
+    "@vitest/coverage-v8": "2.1.9",
+    "coveralls": "^3.0.0",
+    "cpx2": "^3.0.0",
+    "deep-freeze": "^0.0.1",
+    "flow-bin": "^0.123.0",
+    "husky": "^1.2.0",
+    "immutable": "^3.8.2",
+    "import-size": "^1.0.2",
+    "lodash": "^4.17.4",
+    "lodash.clonedeep": "^4.5.0",
+    "prettier": "1.19.1",
+    "pretty-quick": "^1.8.0",
+    "redux": "^4.0.5",
+    "rimraf": "^2.6.2",
+    "seamless-immutable": "^7.1.3",
+    "semantic-release": "^17.0.2",
+    "tsup": "^6.7.0",
+    "type-plus": "^7.6.2",
+    "typescript": "^5.0.2",
+    "vite": "^5.4.0",
+    "vitest": "^2.0.0"
+  }
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/readme.md
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/readme.md	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/readme.md	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,33 @@
+<img src="images/immer-logo.svg" height="200px" align="right"/>
+
+# Immer
+
+[![npm](https://img.shields.io/npm/v/immer.svg)](https://www.npmjs.com/package/immer) [![Build Status](https://github.com/immerjs/immer/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/immerjs/immer/actions?query=branch%3Amain) [![Coverage Status](https://coveralls.io/repos/github/immerjs/immer/badge.svg?branch=main)](https://coveralls.io/github/immerjs/immer?branch=main) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![OpenCollective](https://opencollective.com/immer/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/immer/sponsors/badge.svg)](#sponsors) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/immerjs/immer)
+
+_Create the next immutable state tree by simply modifying the current tree_
+
+Winner of the "Breakthrough of the year" [React open source award](https://osawards.com/react/) and "Most impactful contribution" [JavaScript open source award](https://osawards.com/javascript/) in 2019
+
+## Contribute using one-click online setup
+
+You can use Gitpod (a free online VSCode like IDE) for contributing online. With a single click it will launch a workspace and automatically:
+
+- clone the immer repo.
+- install the dependencies.
+- run `yarn run start`.
+
+so that you can start coding straight away.
+
+[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/from-referrer/)
+
+## Documentation
+
+The documentation of this package is hosted at https://immerjs.github.io/immer/
+
+## Support
+
+Did Immer make a difference to your project? Join the open collective at https://opencollective.com/immer!
+
+## Release notes
+
+https://github.com/immerjs/immer/releases
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/core/current.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/core/current.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/core/current.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,46 @@
+import {
+	die,
+	isDraft,
+	shallowCopy,
+	each,
+	DRAFT_STATE,
+	set,
+	ImmerState,
+	isDraftable,
+	isFrozen
+} from "../internal"
+
+/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */
+export function current<T>(value: T): T
+export function current(value: any): any {
+	if (!isDraft(value)) die(10, value)
+	return currentImpl(value)
+}
+
+function currentImpl(value: any): any {
+	if (!isDraftable(value) || isFrozen(value)) return value
+	const state: ImmerState | undefined = value[DRAFT_STATE]
+	let copy: any
+	let strict = true // Default to strict for compatibility
+	if (state) {
+		if (!state.modified_) return state.base_
+		// Optimization: avoid generating new drafts during copying
+		state.finalized_ = true
+		copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)
+		strict = state.scope_.immer_.shouldUseStrictIteration()
+	} else {
+		copy = shallowCopy(value, true)
+	}
+	// recurse
+	each(
+		copy,
+		(key, childValue) => {
+			set(copy, key, currentImpl(childValue))
+		},
+		strict
+	)
+	if (state) {
+		state.finalized_ = false
+	}
+	return copy
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/core/finalize.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/core/finalize.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/core/finalize.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,318 @@
+import {
+	ImmerScope,
+	DRAFT_STATE,
+	isDraftable,
+	NOTHING,
+	PatchPath,
+	each,
+	freeze,
+	ImmerState,
+	isDraft,
+	SetState,
+	set,
+	ArchType,
+	getPlugin,
+	die,
+	revokeScope,
+	isFrozen,
+	get,
+	Patch,
+	latest,
+	prepareCopy,
+	getFinalValue,
+	getValue,
+	ProxyArrayState
+} from "../internal"
+
+export function processResult(result: any, scope: ImmerScope) {
+	scope.unfinalizedDrafts_ = scope.drafts_.length
+	const baseDraft = scope.drafts_![0]
+	const isReplaced = result !== undefined && result !== baseDraft
+
+	if (isReplaced) {
+		if (baseDraft[DRAFT_STATE].modified_) {
+			revokeScope(scope)
+			die(4)
+		}
+		if (isDraftable(result)) {
+			// Finalize the result in case it contains (or is) a subset of the draft.
+			result = finalize(scope, result)
+		}
+		const {patchPlugin_} = scope
+		if (patchPlugin_) {
+			patchPlugin_.generateReplacementPatches_(
+				baseDraft[DRAFT_STATE].base_,
+				result,
+				scope
+			)
+		}
+	} else {
+		// Finalize the base draft.
+		result = finalize(scope, baseDraft)
+	}
+
+	maybeFreeze(scope, result, true)
+
+	revokeScope(scope)
+	if (scope.patches_) {
+		scope.patchListener_!(scope.patches_, scope.inversePatches_!)
+	}
+	return result !== NOTHING ? result : undefined
+}
+
+function finalize(rootScope: ImmerScope, value: any) {
+	// Don't recurse in tho recursive data structures
+	if (isFrozen(value)) return value
+
+	const state: ImmerState = value[DRAFT_STATE]
+	if (!state) {
+		const finalValue = handleValue(value, rootScope.handledSet_, rootScope)
+		return finalValue
+	}
+
+	// Never finalize drafts owned by another scope
+	if (!isSameScope(state, rootScope)) {
+		return value
+	}
+
+	// Unmodified draft, return the (frozen) original
+	if (!state.modified_) {
+		return state.base_
+	}
+
+	if (!state.finalized_) {
+		// Execute all registered draft finalization callbacks
+		const {callbacks_} = state
+		if (callbacks_) {
+			while (callbacks_.length > 0) {
+				const callback = callbacks_.pop()!
+				callback(rootScope)
+			}
+		}
+
+		generatePatchesAndFinalize(state, rootScope)
+	}
+
+	// By now the root copy has been fully updated throughout its tree
+	return state.copy_
+}
+
+function maybeFreeze(scope: ImmerScope, value: any, deep = false) {
+	// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects
+	if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
+		freeze(value, deep)
+	}
+}
+
+function markStateFinalized(state: ImmerState) {
+	state.finalized_ = true
+	state.scope_.unfinalizedDrafts_--
+}
+
+let isSameScope = (state: ImmerState, rootScope: ImmerScope) =>
+	state.scope_ === rootScope
+
+// A reusable empty array to avoid allocations
+const EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []
+
+// Updates all references to a draft in its parent to the finalized value.
+// This handles cases where the same draft appears multiple times in the parent, or has been moved around.
+export function updateDraftInParent(
+	parent: ImmerState,
+	draftValue: any,
+	finalizedValue: any,
+	originalKey?: string | number | symbol
+): void {
+	const parentCopy = latest(parent)
+	const parentType = parent.type_
+
+	// Fast path: Check if draft is still at original key
+	if (originalKey !== undefined) {
+		const currentValue = get(parentCopy, originalKey, parentType)
+		if (currentValue === draftValue) {
+			// Still at original location, just update it
+			set(parentCopy, originalKey, finalizedValue, parentType)
+			return
+		}
+	}
+
+	// Slow path: Build reverse mapping of all children
+	// to their indices in the parent, so that we can
+	// replace all locations where this draft appears.
+	// We only have to build this once per parent.
+	if (!parent.draftLocations_) {
+		const draftLocations = (parent.draftLocations_ = new Map())
+
+		// Use `each` which works on Arrays, Maps, and Objects
+		each(parentCopy, (key, value) => {
+			if (isDraft(value)) {
+				const keys = draftLocations.get(value) || []
+				keys.push(key)
+				draftLocations.set(value, keys)
+			}
+		})
+	}
+
+	// Look up all locations where this draft appears
+	const locations =
+		parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT
+
+	// Update all locations
+	for (const location of locations) {
+		set(parentCopy, location, finalizedValue, parentType)
+	}
+}
+
+// Register a callback to finalize a child draft when the parent draft is finalized.
+// This assumes there is a parent -> child relationship between the two drafts,
+// and we have a key to locate the child in the parent.
+export function registerChildFinalizationCallback(
+	parent: ImmerState,
+	child: ImmerState,
+	key: string | number | symbol
+) {
+	parent.callbacks_.push(function childCleanup(rootScope) {
+		const state: ImmerState = child
+
+		// Can only continue if this is a draft owned by this scope
+		if (!state || !isSameScope(state, rootScope)) {
+			return
+		}
+
+		// Handle potential set value finalization first
+		rootScope.mapSetPlugin_?.fixSetContents(state)
+
+		const finalizedValue = getFinalValue(state)
+
+		// Update all locations in the parent that referenced this draft
+		updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)
+
+		generatePatchesAndFinalize(state, rootScope)
+	})
+}
+
+function generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {
+	const shouldFinalize =
+		state.modified_ &&
+		!state.finalized_ &&
+		(state.type_ === ArchType.Set ||
+			(state.type_ === ArchType.Array &&
+				(state as ProxyArrayState).allIndicesReassigned_) ||
+			(state.assigned_?.size ?? 0) > 0)
+
+	if (shouldFinalize) {
+		const {patchPlugin_} = rootScope
+		if (patchPlugin_) {
+			const basePath = patchPlugin_!.getPath(state)
+
+			if (basePath) {
+				patchPlugin_!.generatePatches_(state, basePath, rootScope)
+			}
+		}
+
+		markStateFinalized(state)
+	}
+}
+
+export function handleCrossReference(
+	target: ImmerState,
+	key: string | number | symbol,
+	value: any
+) {
+	const {scope_} = target
+	// Check if value is a draft from this scope
+	if (isDraft(value)) {
+		const state: ImmerState = value[DRAFT_STATE]
+		if (isSameScope(state, scope_)) {
+			// Register callback to update this location when the draft finalizes
+
+			state.callbacks_.push(function crossReferenceCleanup() {
+				// Update the target location with finalized value
+				prepareCopy(target)
+
+				const finalizedValue = getFinalValue(state)
+
+				updateDraftInParent(target, value, finalizedValue, key)
+			})
+		}
+	} else if (isDraftable(value)) {
+		// Handle non-draft objects that might contain drafts
+		target.callbacks_.push(function nestedDraftCleanup() {
+			const targetCopy = latest(target)
+
+			// For Sets, check if value is still in the set
+			if (target.type_ === ArchType.Set) {
+				if (targetCopy.has(value)) {
+					// Process the value to replace any nested drafts
+					handleValue(value, scope_.handledSet_, scope_)
+				}
+			} else {
+				// Maps/objects
+				if (get(targetCopy, key, target.type_) === value) {
+					if (
+						scope_.drafts_.length > 1 &&
+						((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??
+							false) === true &&
+						target.copy_
+					) {
+						// This might be a non-draft value that has drafts
+						// inside. We do need to recurse here to handle those.
+						handleValue(
+							get(target.copy_, key, target.type_),
+							scope_.handledSet_,
+							scope_
+						)
+					}
+				}
+			}
+		})
+	}
+}
+
+export function handleValue(
+	target: any,
+	handledSet: Set<any>,
+	rootScope: ImmerScope
+) {
+	if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
+		// optimization: if an object is not a draft, and we don't have to
+		// deepfreeze everything, and we are sure that no drafts are left in the remaining object
+		// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.
+		// This benefits especially adding large data tree's without further processing.
+		// See add-data.js perf test
+		return target
+	}
+
+	// Skip if already handled, frozen, or not draftable
+	if (
+		isDraft(target) ||
+		handledSet.has(target) ||
+		!isDraftable(target) ||
+		isFrozen(target)
+	) {
+		return target
+	}
+
+	handledSet.add(target)
+
+	// Process ALL properties/entries
+	each(target, (key, value) => {
+		if (isDraft(value)) {
+			const state: ImmerState = value[DRAFT_STATE]
+			if (isSameScope(state, rootScope)) {
+				// Replace draft with finalized value
+
+				const updatedValue = getFinalValue(state)
+
+				set(target, key, updatedValue, target.type_)
+
+				markStateFinalized(state)
+			}
+		} else if (isDraftable(value)) {
+			// Recursively handle nested values
+			handleValue(value, handledSet, rootScope)
+		}
+	})
+
+	return target
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/core/immerClass.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/core/immerClass.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/core/immerClass.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,273 @@
+import {
+	IProduceWithPatches,
+	IProduce,
+	ImmerState,
+	Drafted,
+	isDraftable,
+	processResult,
+	Patch,
+	Objectish,
+	DRAFT_STATE,
+	Draft,
+	PatchListener,
+	isDraft,
+	isMap,
+	isSet,
+	createProxyProxy,
+	getPlugin,
+	die,
+	enterScope,
+	revokeScope,
+	leaveScope,
+	usePatchesInScope,
+	getCurrentScope,
+	NOTHING,
+	freeze,
+	current,
+	ImmerScope,
+	registerChildFinalizationCallback,
+	ArchType,
+	MapSetPlugin,
+	AnyMap,
+	AnySet,
+	isObjectish,
+	isFunction,
+	isBoolean,
+	PluginMapSet,
+	PluginPatches
+} from "../internal"
+
+interface ProducersFns {
+	produce: IProduce
+	produceWithPatches: IProduceWithPatches
+}
+
+export type StrictMode = boolean | "class_only"
+
+export class Immer implements ProducersFns {
+	autoFreeze_: boolean = true
+	useStrictShallowCopy_: StrictMode = false
+	useStrictIteration_: boolean = false
+
+	constructor(config?: {
+		autoFreeze?: boolean
+		useStrictShallowCopy?: StrictMode
+		useStrictIteration?: boolean
+	}) {
+		if (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)
+		if (isBoolean(config?.useStrictShallowCopy))
+			this.setUseStrictShallowCopy(config!.useStrictShallowCopy)
+		if (isBoolean(config?.useStrictIteration))
+			this.setUseStrictIteration(config!.useStrictIteration)
+	}
+
+	/**
+	 * The `produce` function takes a value and a "recipe function" (whose
+	 * return value often depends on the base state). The recipe function is
+	 * free to mutate its first argument however it wants. All mutations are
+	 * only ever applied to a __copy__ of the base state.
+	 *
+	 * Pass only a function to create a "curried producer" which relieves you
+	 * from passing the recipe function every time.
+	 *
+	 * Only plain objects and arrays are made mutable. All other objects are
+	 * considered uncopyable.
+	 *
+	 * Note: This function is __bound__ to its `Immer` instance.
+	 *
+	 * @param {any} base - the initial state
+	 * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
+	 * @param {Function} patchListener - optional function that will be called with all the patches produced here
+	 * @returns {any} a new state, or the initial state if nothing was modified
+	 */
+	produce: IProduce = (base: any, recipe?: any, patchListener?: any) => {
+		// curried invocation
+		if (isFunction(base) && !isFunction(recipe)) {
+			const defaultBase = recipe
+			recipe = base
+
+			const self = this
+			return function curriedProduce(
+				this: any,
+				base = defaultBase,
+				...args: any[]
+			) {
+				return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore
+			}
+		}
+
+		if (!isFunction(recipe)) die(6)
+		if (patchListener !== undefined && !isFunction(patchListener)) die(7)
+
+		let result
+
+		// Only plain objects, arrays, and "immerable classes" are drafted.
+		if (isDraftable(base)) {
+			const scope = enterScope(this)
+			const proxy = createProxy(scope, base, undefined)
+			let hasError = true
+			try {
+				result = recipe(proxy)
+				hasError = false
+			} finally {
+				// finally instead of catch + rethrow better preserves original stack
+				if (hasError) revokeScope(scope)
+				else leaveScope(scope)
+			}
+			usePatchesInScope(scope, patchListener)
+			return processResult(result, scope)
+		} else if (!base || !isObjectish(base)) {
+			result = recipe(base)
+			if (result === undefined) result = base
+			if (result === NOTHING) result = undefined
+			if (this.autoFreeze_) freeze(result, true)
+			if (patchListener) {
+				const p: Patch[] = []
+				const ip: Patch[] = []
+				getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
+					patches_: p,
+					inversePatches_: ip
+				} as ImmerScope) // dummy scope
+				patchListener(p, ip)
+			}
+			return result
+		} else die(1, base)
+	}
+
+	produceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {
+		// curried invocation
+		if (isFunction(base)) {
+			return (state: any, ...args: any[]) =>
+				this.produceWithPatches(state, (draft: any) => base(draft, ...args))
+		}
+
+		let patches: Patch[], inversePatches: Patch[]
+		const result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {
+			patches = p
+			inversePatches = ip
+		})
+		return [result, patches!, inversePatches!]
+	}
+
+	createDraft<T extends Objectish>(base: T): Draft<T> {
+		if (!isDraftable(base)) die(8)
+		if (isDraft(base)) base = current(base)
+		const scope = enterScope(this)
+		const proxy = createProxy(scope, base, undefined)
+		proxy[DRAFT_STATE].isManual_ = true
+		leaveScope(scope)
+		return proxy as any
+	}
+
+	finishDraft<D extends Draft<any>>(
+		draft: D,
+		patchListener?: PatchListener
+	): D extends Draft<infer T> ? T : never {
+		const state: ImmerState = draft && (draft as any)[DRAFT_STATE]
+		if (!state || !state.isManual_) die(9)
+		const {scope_: scope} = state
+		usePatchesInScope(scope, patchListener)
+		return processResult(undefined, scope)
+	}
+
+	/**
+	 * Pass true to automatically freeze all copies created by Immer.
+	 *
+	 * By default, auto-freezing is enabled.
+	 */
+	setAutoFreeze(value: boolean) {
+		this.autoFreeze_ = value
+	}
+
+	/**
+	 * Pass true to enable strict shallow copy.
+	 *
+	 * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+	 */
+	setUseStrictShallowCopy(value: StrictMode) {
+		this.useStrictShallowCopy_ = value
+	}
+
+	/**
+	 * Pass false to use faster iteration that skips non-enumerable properties
+	 * but still handles symbols for compatibility.
+	 *
+	 * By default, strict iteration is enabled (includes all own properties).
+	 */
+	setUseStrictIteration(value: boolean) {
+		this.useStrictIteration_ = value
+	}
+
+	shouldUseStrictIteration(): boolean {
+		return this.useStrictIteration_
+	}
+
+	applyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {
+		// If a patch replaces the entire state, take that replacement as base
+		// before applying patches
+		let i: number
+		for (i = patches.length - 1; i >= 0; i--) {
+			const patch = patches[i]
+			if (patch.path.length === 0 && patch.op === "replace") {
+				base = patch.value
+				break
+			}
+		}
+		// If there was a patch that replaced the entire state, start from the
+		// patch after that.
+		if (i > -1) {
+			patches = patches.slice(i + 1)
+		}
+
+		const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_
+		if (isDraft(base)) {
+			// N.B: never hits if some patch a replacement, patches are never drafts
+			return applyPatchesImpl(base, patches)
+		}
+		// Otherwise, produce a copy of the base state.
+		return this.produce(base, (draft: Drafted) =>
+			applyPatchesImpl(draft, patches)
+		)
+	}
+}
+
+export function createProxy<T extends Objectish>(
+	rootScope: ImmerScope,
+	value: T,
+	parent?: ImmerState,
+	key?: string | number | symbol
+): Drafted<T, ImmerState> {
+	// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft
+	// returning a tuple here lets us skip a proxy access
+	// to DRAFT_STATE later
+	const [draft, state] = isMap(value)
+		? getPlugin(PluginMapSet).proxyMap_(value, parent)
+		: isSet(value)
+		? getPlugin(PluginMapSet).proxySet_(value, parent)
+		: createProxyProxy(value, parent)
+
+	const scope = parent?.scope_ ?? getCurrentScope()
+	scope.drafts_.push(draft)
+
+	// Ensure the parent callbacks are passed down so we actually
+	// track all callbacks added throughout the tree
+	state.callbacks_ = parent?.callbacks_ ?? []
+	state.key_ = key
+
+	if (parent && key !== undefined) {
+		registerChildFinalizationCallback(parent, state, key)
+	} else {
+		// It's a root draft, register it with the scope
+		state.callbacks_.push(function rootDraftCleanup(rootScope) {
+			rootScope.mapSetPlugin_?.fixSetContents(state)
+
+			const {patchPlugin_} = rootScope
+
+			if (state.modified_ && patchPlugin_) {
+				patchPlugin_.generatePatches_(state, [], rootScope)
+			}
+		})
+	}
+
+	return draft as any
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/core/proxy.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/core/proxy.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/core/proxy.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,336 @@
+import {
+	has,
+	is,
+	isDraftable,
+	shallowCopy,
+	latest,
+	ImmerBaseState,
+	ImmerState,
+	Drafted,
+	AnyObject,
+	AnyArray,
+	Objectish,
+	getCurrentScope,
+	getPrototypeOf,
+	DRAFT_STATE,
+	die,
+	createProxy,
+	ArchType,
+	handleCrossReference,
+	WRITABLE,
+	CONFIGURABLE,
+	ENUMERABLE,
+	VALUE,
+	isArray,
+	isArrayIndex
+} from "../internal"
+
+interface ProxyBaseState extends ImmerBaseState {
+	parent_?: ImmerState
+	revoke_(): void
+}
+
+export interface ProxyObjectState extends ProxyBaseState {
+	type_: ArchType.Object
+	base_: any
+	copy_: any
+	draft_: Drafted<AnyObject, ProxyObjectState>
+}
+
+export interface ProxyArrayState extends ProxyBaseState {
+	type_: ArchType.Array
+	base_: AnyArray
+	copy_: AnyArray | null
+	draft_: Drafted<AnyArray, ProxyArrayState>
+	operationMethod?: string
+	allIndicesReassigned_?: boolean
+}
+
+type ProxyState = ProxyObjectState | ProxyArrayState
+
+/**
+ * Returns a new draft of the `base` object.
+ *
+ * The second argument is the parent draft-state (used internally).
+ */
+export function createProxyProxy<T extends Objectish>(
+	base: T,
+	parent?: ImmerState
+): [Drafted<T, ProxyState>, ProxyState] {
+	const baseIsArray = isArray(base)
+	const state: ProxyState = {
+		type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),
+		// Track which produce call this is associated with.
+		scope_: parent ? parent.scope_ : getCurrentScope()!,
+		// True for both shallow and deep changes.
+		modified_: false,
+		// Used during finalization.
+		finalized_: false,
+		// Track which properties have been assigned (true) or deleted (false).
+		// actually instantiated in `prepareCopy()`
+		assigned_: undefined,
+		// The parent draft state.
+		parent_: parent,
+		// The base state.
+		base_: base,
+		// The base proxy.
+		draft_: null as any, // set below
+		// The base copy with any updated values.
+		copy_: null,
+		// Called by the `produce` function.
+		revoke_: null as any,
+		isManual_: false,
+		// `callbacks` actually gets assigned in `createProxy`
+		callbacks_: undefined as any
+	}
+
+	// the traps must target something, a bit like the 'real' base.
+	// but also, we need to be able to determine from the target what the relevant state is
+	// (to avoid creating traps per instance to capture the state in closure,
+	// and to avoid creating weird hidden properties as well)
+	// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)
+	// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb
+	let target: T = state as any
+	let traps: ProxyHandler<object | Array<any>> = objectTraps
+	if (baseIsArray) {
+		target = [state] as any
+		traps = arrayTraps
+	}
+
+	const {revoke, proxy} = Proxy.revocable(target, traps)
+	state.draft_ = proxy as any
+	state.revoke_ = revoke
+	return [proxy as any, state]
+}
+
+/**
+ * Object drafts
+ */
+export const objectTraps: ProxyHandler<ProxyState> = {
+	get(state, prop) {
+		if (prop === DRAFT_STATE) return state
+
+		let arrayPlugin = state.scope_.arrayMethodsPlugin_
+		const isArrayWithStringProp =
+			state.type_ === ArchType.Array && typeof prop === "string"
+		// Intercept array methods so that we can override
+		// behavior and skip proxy creation for perf
+		if (isArrayWithStringProp) {
+			if (arrayPlugin?.isArrayOperationMethod(prop)) {
+				return arrayPlugin.createMethodInterceptor(state, prop)
+			}
+		}
+
+		const source = latest(state)
+		if (!has(source, prop, state.type_)) {
+			// non-existing or non-own property...
+			return readPropFromProto(state, source, prop)
+		}
+		const value = source[prop]
+		if (state.finalized_ || !isDraftable(value)) {
+			return value
+		}
+
+		// During mutating array operations, defer proxy creation for array elements
+		// This optimization avoids creating unnecessary proxies during sort/reverse
+		if (
+			isArrayWithStringProp &&
+			(state as ProxyArrayState).operationMethod &&
+			arrayPlugin?.isMutatingArrayMethod(
+				(state as ProxyArrayState).operationMethod!
+			) &&
+			isArrayIndex(prop)
+		) {
+			// Return raw value during mutating operations, create proxy only if modified
+			return value
+		}
+		// Check for existing draft in modified state.
+		// Assigned values are never drafted. This catches any drafts we created, too.
+		if (value === peek(state.base_, prop)) {
+			prepareCopy(state)
+			// Ensure array keys are always numbers
+			const childKey = state.type_ === ArchType.Array ? +(prop as string) : prop
+			const childDraft = createProxy(state.scope_, value, state, childKey)
+
+			return (state.copy_![childKey] = childDraft)
+		}
+		return value
+	},
+	has(state, prop) {
+		return prop in latest(state)
+	},
+	ownKeys(state) {
+		return Reflect.ownKeys(latest(state))
+	},
+	set(
+		state: ProxyObjectState,
+		prop: string /* strictly not, but helps TS */,
+		value
+	) {
+		const desc = getDescriptorFromProto(latest(state), prop)
+		if (desc?.set) {
+			// special case: if this write is captured by a setter, we have
+			// to trigger it with the correct context
+			desc.set.call(state.draft_, value)
+			return true
+		}
+		if (!state.modified_) {
+			// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)
+			// from setting an existing property with value undefined to undefined (which is not a change)
+			const current = peek(latest(state), prop)
+			// special case, if we assigning the original value to a draft, we can ignore the assignment
+			const currentState: ProxyObjectState = current?.[DRAFT_STATE]
+			if (currentState && currentState.base_ === value) {
+				state.copy_![prop] = value
+				state.assigned_!.set(prop, false)
+				return true
+			}
+			if (
+				is(value, current) &&
+				(value !== undefined || has(state.base_, prop, state.type_))
+			)
+				return true
+			prepareCopy(state)
+			markChanged(state)
+		}
+
+		if (
+			(state.copy_![prop] === value &&
+				// special case: handle new props with value 'undefined'
+				(value !== undefined || prop in state.copy_)) ||
+			// special case: NaN
+			(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))
+		)
+			return true
+
+		// @ts-ignore
+		state.copy_![prop] = value
+		state.assigned_!.set(prop, true)
+
+		handleCrossReference(state, prop, value)
+		return true
+	},
+	deleteProperty(state, prop: string) {
+		prepareCopy(state)
+		// The `undefined` check is a fast path for pre-existing keys.
+		if (peek(state.base_, prop) !== undefined || prop in state.base_) {
+			state.assigned_!.set(prop, false)
+			markChanged(state)
+		} else {
+			// if an originally not assigned property was deleted
+			state.assigned_!.delete(prop)
+		}
+		if (state.copy_) {
+			delete state.copy_[prop]
+		}
+		return true
+	},
+	// Note: We never coerce `desc.value` into an Immer draft, because we can't make
+	// the same guarantee in ES5 mode.
+	getOwnPropertyDescriptor(state, prop) {
+		const owner = latest(state)
+		const desc = Reflect.getOwnPropertyDescriptor(owner, prop)
+		if (!desc) return desc
+		return {
+			[WRITABLE]: true,
+			[CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== "length",
+			[ENUMERABLE]: desc[ENUMERABLE],
+			[VALUE]: owner[prop]
+		}
+	},
+	defineProperty() {
+		die(11)
+	},
+	getPrototypeOf(state) {
+		return getPrototypeOf(state.base_)
+	},
+	setPrototypeOf() {
+		die(12)
+	}
+}
+
+/**
+ * Array drafts
+ */
+
+const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}
+// Use `for..in` instead of `each` to work around a weird
+// prod test suite issue
+for (let key in objectTraps) {
+	let fn = objectTraps[key as keyof typeof objectTraps] as Function
+	// @ts-ignore
+	arrayTraps[key] = function() {
+		const args = arguments
+		args[0] = args[0][0]
+		return fn.apply(this, args)
+	}
+}
+arrayTraps.deleteProperty = function(state, prop) {
+	if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))
+		die(13)
+	// @ts-ignore
+	return arrayTraps.set!.call(this, state, prop, undefined)
+}
+arrayTraps.set = function(state, prop, value) {
+	if (
+		process.env.NODE_ENV !== "production" &&
+		prop !== "length" &&
+		isNaN(parseInt(prop as any))
+	)
+		die(14)
+	return objectTraps.set!.call(this, state[0], prop, value, state[0])
+}
+
+// Access a property without creating an Immer draft.
+function peek(draft: Drafted, prop: PropertyKey) {
+	const state = draft[DRAFT_STATE]
+	const source = state ? latest(state) : draft
+	return source[prop]
+}
+
+function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {
+	const desc = getDescriptorFromProto(source, prop)
+	return desc
+		? VALUE in desc
+			? desc[VALUE]
+			: // This is a very special case, if the prop is a getter defined by the
+			  // prototype, we should invoke it with the draft as context!
+			  desc.get?.call(state.draft_)
+		: undefined
+}
+
+function getDescriptorFromProto(
+	source: any,
+	prop: PropertyKey
+): PropertyDescriptor | undefined {
+	// 'in' checks proto!
+	if (!(prop in source)) return undefined
+	let proto = getPrototypeOf(source)
+	while (proto) {
+		const desc = Object.getOwnPropertyDescriptor(proto, prop)
+		if (desc) return desc
+		proto = getPrototypeOf(proto)
+	}
+	return undefined
+}
+
+export function markChanged(state: ImmerState) {
+	if (!state.modified_) {
+		state.modified_ = true
+		if (state.parent_) {
+			markChanged(state.parent_)
+		}
+	}
+}
+
+export function prepareCopy(state: ImmerState) {
+	if (!state.copy_) {
+		// Actually create the `assigned_` map now that we
+		// know this is a modified draft.
+		state.assigned_ = new Map()
+		state.copy_ = shallowCopy(
+			state.base_,
+			state.scope_.immer_.useStrictShallowCopy_
+		)
+	}
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/core/scope.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/core/scope.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/core/scope.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,95 @@
+import {
+	Patch,
+	PatchListener,
+	Drafted,
+	Immer,
+	DRAFT_STATE,
+	ImmerState,
+	ArchType,
+	getPlugin,
+	PatchesPlugin,
+	MapSetPlugin,
+	isPluginLoaded,
+	PluginMapSet,
+	PluginPatches,
+	ArrayMethodsPlugin,
+	PluginArrayMethods
+} from "../internal"
+
+/** Each scope represents a `produce` call. */
+
+export interface ImmerScope {
+	patches_?: Patch[]
+	inversePatches_?: Patch[]
+	patchPlugin_?: PatchesPlugin
+	mapSetPlugin_?: MapSetPlugin
+	arrayMethodsPlugin_?: ArrayMethodsPlugin
+	canAutoFreeze_: boolean
+	drafts_: any[]
+	parent_?: ImmerScope
+	patchListener_?: PatchListener
+	immer_: Immer
+	unfinalizedDrafts_: number
+	handledSet_: Set<any>
+	processedForPatches_: Set<any>
+}
+
+let currentScope: ImmerScope | undefined
+
+export let getCurrentScope = () => currentScope!
+
+let createScope = (
+	parent_: ImmerScope | undefined,
+	immer_: Immer
+): ImmerScope => ({
+	drafts_: [],
+	parent_,
+	immer_,
+	// Whenever the modified draft contains a draft from another scope, we
+	// need to prevent auto-freezing so the unowned draft can be finalized.
+	canAutoFreeze_: true,
+	unfinalizedDrafts_: 0,
+	handledSet_: new Set(),
+	processedForPatches_: new Set(),
+	mapSetPlugin_: isPluginLoaded(PluginMapSet)
+		? getPlugin(PluginMapSet)
+		: undefined,
+	arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods)
+		? getPlugin(PluginArrayMethods)
+		: undefined
+})
+
+export function usePatchesInScope(
+	scope: ImmerScope,
+	patchListener?: PatchListener
+) {
+	if (patchListener) {
+		scope.patchPlugin_ = getPlugin(PluginPatches) // assert we have the plugin
+		scope.patches_ = []
+		scope.inversePatches_ = []
+		scope.patchListener_ = patchListener
+	}
+}
+
+export function revokeScope(scope: ImmerScope) {
+	leaveScope(scope)
+	scope.drafts_.forEach(revokeDraft)
+	// @ts-ignore
+	scope.drafts_ = null
+}
+
+export function leaveScope(scope: ImmerScope) {
+	if (scope === currentScope) {
+		currentScope = scope.parent_
+	}
+}
+
+export let enterScope = (immer: Immer) =>
+	(currentScope = createScope(currentScope, immer))
+
+function revokeDraft(draft: Drafted) {
+	const state: ImmerState = draft[DRAFT_STATE]
+	if (state.type_ === ArchType.Object || state.type_ === ArchType.Array)
+		state.revoke_()
+	else state.revoked_ = true
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/immer.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/immer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/immer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,126 @@
+import {
+	IProduce,
+	IProduceWithPatches,
+	Immer,
+	Draft,
+	Immutable
+} from "./internal"
+
+export {
+	Draft,
+	WritableDraft,
+	Immutable,
+	Patch,
+	PatchListener,
+	Producer,
+	original,
+	current,
+	isDraft,
+	isDraftable,
+	NOTHING as nothing,
+	DRAFTABLE as immerable,
+	freeze,
+	Objectish,
+	StrictMode
+} from "./internal"
+
+const immer = new Immer()
+
+/**
+ * The `produce` function takes a value and a "recipe function" (whose
+ * return value often depends on the base state). The recipe function is
+ * free to mutate its first argument however it wants. All mutations are
+ * only ever applied to a __copy__ of the base state.
+ *
+ * Pass only a function to create a "curried producer" which relieves you
+ * from passing the recipe function every time.
+ *
+ * Only plain objects and arrays are made mutable. All other objects are
+ * considered uncopyable.
+ *
+ * Note: This function is __bound__ to its `Immer` instance.
+ *
+ * @param {any} base - the initial state
+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
+ * @returns {any} a new state, or the initial state if nothing was modified
+ */
+export const produce: IProduce = /* @__PURE__ */ immer.produce
+
+/**
+ * Like `produce`, but `produceWithPatches` always returns a tuple
+ * [nextState, patches, inversePatches] (instead of just the next state)
+ */
+export const produceWithPatches: IProduceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(
+	immer
+)
+
+/**
+ * Pass true to automatically freeze all copies created by Immer.
+ *
+ * Always freeze by default, even in production mode
+ */
+export const setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer)
+
+/**
+ * Pass true to enable strict shallow copy.
+ *
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+ */
+export const setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(
+	immer
+)
+
+/**
+ * Pass false to use loose iteration that only processes enumerable string properties.
+ * This skips symbols and non-enumerable properties for maximum performance.
+ *
+ * By default, strict iteration is enabled (includes all own properties).
+ */
+export const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(
+	immer
+)
+
+/**
+ * Apply an array of Immer patches to the first argument.
+ *
+ * This function is a producer, which means copy-on-write is in effect.
+ */
+export const applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer)
+
+/**
+ * Create an Immer draft from the given base state, which may be a draft itself.
+ * The draft can be modified until you finalize it with the `finishDraft` function.
+ */
+export const createDraft = /* @__PURE__ */ immer.createDraft.bind(immer)
+
+/**
+ * Finalize an Immer draft from a `createDraft` call, returning the base state
+ * (if no changes were made) or a modified copy. The draft must *not* be
+ * mutated afterwards.
+ *
+ * Pass a function as the 2nd argument to generate Immer patches based on the
+ * changes that were made.
+ */
+export const finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer)
+
+/**
+ * This function is actually a no-op, but can be used to cast an immutable type
+ * to an draft type and make TypeScript happy
+ *
+ * @param value
+ */
+export let castDraft = <T>(value: T): Draft<T> => value as any
+
+/**
+ * This function is actually a no-op, but can be used to cast a mutable type
+ * to an immutable type and make TypeScript happy
+ * @param value
+ */
+export let castImmutable = <T>(value: T): Immutable<T> => value as any
+
+export {Immer}
+
+export {enablePatches} from "./plugins/patches"
+export {enableMapSet} from "./plugins/mapset"
+export {enableArrayMethods} from "./plugins/arrayMethods"
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/internal.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/internal.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/internal.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,11 @@
+export * from "./utils/env"
+export * from "./utils/errors"
+export * from "./types/types-external"
+export * from "./types/types-internal"
+export * from "./utils/common"
+export * from "./utils/plugins"
+export * from "./core/scope"
+export * from "./core/finalize"
+export * from "./core/proxy"
+export * from "./core/immerClass"
+export * from "./core/current"
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/arrayMethods.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/arrayMethods.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/arrayMethods.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,395 @@
+import {
+	PluginArrayMethods,
+	latest,
+	loadPlugin,
+	markChanged,
+	prepareCopy,
+	ProxyArrayState
+} from "../internal"
+
+/**
+ * Methods that directly modify the array in place.
+ * These operate on the copy without creating per-element proxies:
+ * - `push`, `pop`: Add/remove from end
+ * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)
+ * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)
+ * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)
+ */
+type MutatingArrayMethod =
+	| "push"
+	| "pop"
+	| "shift"
+	| "unshift"
+	| "splice"
+	| "reverse"
+	| "sort"
+
+/**
+ * Methods that read from the array without modifying it.
+ * These fall into distinct categories based on return semantics:
+ *
+ * **Subset operations** (return drafts - mutations propagate):
+ * - `filter`, `slice`: Return array of draft proxies
+ * - `find`, `findLast`: Return single draft proxy or undefined
+ *
+ * **Transform operations** (return base values - mutations don't track):
+ * - `concat`, `flat`: Create new structures, not subsets of original
+ *
+ * **Primitive-returning** (no draft needed):
+ * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers
+ * - `some`, `every`, `includes`: Return booleans
+ * - `join`, `toString`, `toLocaleString`: Return strings
+ */
+type NonMutatingArrayMethod =
+	| "filter"
+	| "slice"
+	| "concat"
+	| "flat"
+	| "find"
+	| "findIndex"
+	| "findLast"
+	| "findLastIndex"
+	| "some"
+	| "every"
+	| "indexOf"
+	| "lastIndexOf"
+	| "includes"
+	| "join"
+	| "toString"
+	| "toLocaleString"
+
+/** Union of all array operation methods handled by the plugin. */
+export type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod
+
+/**
+ * Enables optimized array method handling for Immer drafts.
+ *
+ * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,
+ * significantly improving performance for array-heavy operations.
+ *
+ * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):
+ * Operate directly on the copy without creating per-element proxies.
+ *
+ * **Non-mutating methods** fall into categories:
+ * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track
+ * - **Transform operations** (concat, flat): Return base values - mutations don't track
+ * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives
+ *
+ * **Important**: Callbacks for overridden methods receive base values, not drafts.
+ * This is the core performance optimization.
+ *
+ * @example
+ * ```ts
+ * import { enableArrayMethods, produce } from "immer"
+ *
+ * enableArrayMethods()
+ *
+ * const next = produce(state, draft => {
+ *   // Optimized - no proxy creation per element
+ *   draft.items.sort((a, b) => a.value - b.value)
+ *
+ *   // filter returns drafts - mutations propagate
+ *   const filtered = draft.items.filter(x => x.value > 5)
+ *   filtered[0].value = 999 // Affects draft.items[originalIndex]
+ * })
+ * ```
+ *
+ * @see https://immerjs.github.io/immer/array-methods
+ */
+export function enableArrayMethods() {
+	const SHIFTING_METHODS = new Set<MutatingArrayMethod>(["shift", "unshift"])
+
+	const QUEUE_METHODS = new Set<MutatingArrayMethod>(["push", "pop"])
+
+	const RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([
+		...QUEUE_METHODS,
+		...SHIFTING_METHODS
+	])
+
+	const REORDERING_METHODS = new Set<MutatingArrayMethod>(["reverse", "sort"])
+
+	// Optimized method detection using array-based lookup
+	const MUTATING_METHODS = new Set<MutatingArrayMethod>([
+		...RESULT_RETURNING_METHODS,
+		...REORDERING_METHODS,
+		"splice"
+	])
+
+	const FIND_METHODS = new Set<NonMutatingArrayMethod>(["find", "findLast"])
+
+	const NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([
+		"filter",
+		"slice",
+		"concat",
+		"flat",
+		...FIND_METHODS,
+		"findIndex",
+		"findLastIndex",
+		"some",
+		"every",
+		"indexOf",
+		"lastIndexOf",
+		"includes",
+		"join",
+		"toString",
+		"toLocaleString"
+	])
+
+	// Type guard for method detection
+	function isMutatingArrayMethod(
+		method: string
+	): method is MutatingArrayMethod {
+		return MUTATING_METHODS.has(method as any)
+	}
+
+	function isNonMutatingArrayMethod(
+		method: string
+	): method is NonMutatingArrayMethod {
+		return NON_MUTATING_METHODS.has(method as any)
+	}
+
+	function isArrayOperationMethod(
+		method: string
+	): method is ArrayOperationMethod {
+		return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)
+	}
+
+	function enterOperation(
+		state: ProxyArrayState,
+		method: ArrayOperationMethod
+	) {
+		state.operationMethod = method
+	}
+
+	function exitOperation(state: ProxyArrayState) {
+		state.operationMethod = undefined
+	}
+
+	// Shared utility functions for array method handlers
+	function executeArrayMethod<T>(
+		state: ProxyArrayState,
+		operation: () => T,
+		markLength = true
+	): T {
+		prepareCopy(state)
+		const result = operation()
+		markChanged(state)
+		if (markLength) state.assigned_!.set("length", true)
+		return result
+	}
+
+	function markAllIndicesReassigned(state: ProxyArrayState) {
+		state.allIndicesReassigned_ = true
+	}
+
+	function normalizeSliceIndex(index: number, length: number): number {
+		if (index < 0) {
+			return Math.max(length + index, 0)
+		}
+		return Math.min(index, length)
+	}
+
+	/**
+	 * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).
+	 *
+	 * Operates directly on `state.copy_` without creating per-element proxies.
+	 * For shifting methods (shift, unshift), marks all indices as reassigned since
+	 * indices shift.
+	 *
+	 * @returns For push/pop/shift/unshift: the native method result. For others: the draft.
+	 */
+	function handleSimpleOperation(
+		state: ProxyArrayState,
+		method: string,
+		args: any[]
+	) {
+		return executeArrayMethod(state, () => {
+			const result = (state.copy_! as any)[method](...args)
+
+			// Handle index reassignment for shifting methods
+			if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {
+				markAllIndicesReassigned(state)
+			}
+
+			// Return appropriate value based on method
+			return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)
+				? result
+				: state.draft_
+		})
+	}
+
+	/**
+	 * Handles reordering operations (reverse, sort) that change element order.
+	 *
+	 * Operates directly on `state.copy_` and marks all indices as reassigned
+	 * since element positions change. Does not mark length as changed since
+	 * these operations preserve array length.
+	 *
+	 * @returns The draft proxy for method chaining.
+	 */
+	function handleReorderingOperation(
+		state: ProxyArrayState,
+		method: string,
+		args: any[]
+	) {
+		return executeArrayMethod(
+			state,
+			() => {
+				;(state.copy_! as any)[method](...args)
+				markAllIndicesReassigned(state)
+				return state.draft_
+			},
+			false
+		) // Don't mark length as changed
+	}
+
+	/**
+	 * Creates an interceptor function for a specific array method.
+	 *
+	 * The interceptor wraps array method calls to:
+	 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap
+	 *    to detect we're inside an optimized method and skip proxy creation)
+	 * 2. Route to appropriate handler based on method type
+	 * 3. Clean up the operation flag in `finally` block
+	 *
+	 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`
+	 * trap to return base values instead of creating nested proxies during iteration.
+	 *
+	 * @param state - The proxy array state
+	 * @param originalMethod - Name of the array method being intercepted
+	 * @returns Interceptor function that handles the method call
+	 */
+	function createMethodInterceptor(
+		state: ProxyArrayState,
+		originalMethod: string
+	) {
+		return function interceptedMethod(...args: any[]) {
+			// Enter operation mode - this flag tells the proxy's get trap to return
+			// base values instead of creating nested proxies during iteration
+			const method = originalMethod as ArrayOperationMethod
+			enterOperation(state, method)
+
+			try {
+				// Check if this is a mutating method
+				if (isMutatingArrayMethod(method)) {
+					// Direct method dispatch - no configuration lookup needed
+					if (RESULT_RETURNING_METHODS.has(method)) {
+						return handleSimpleOperation(state, method, args)
+					}
+					if (REORDERING_METHODS.has(method)) {
+						return handleReorderingOperation(state, method, args)
+					}
+
+					if (method === "splice") {
+						const res = executeArrayMethod(state, () =>
+							state.copy_!.splice(...(args as [number, number, ...any[]]))
+						)
+						markAllIndicesReassigned(state)
+						return res
+					}
+				} else {
+					// Handle non-mutating methods
+					return handleNonMutatingOperation(state, method, args)
+				}
+			} finally {
+				// Always exit operation mode - must be in finally to handle exceptions
+				exitOperation(state)
+			}
+		}
+	}
+
+	/**
+	 * Handles non-mutating array methods with different return semantics.
+	 *
+	 * **Subset operations** return draft proxies for mutation tracking:
+	 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element
+	 * - `find`, `findLast`: Return `state.draft_[i]` for the found element
+	 *
+	 * This allows mutations on returned elements to propagate back to the draft:
+	 * ```ts
+	 * const filtered = draft.items.filter(x => x.value > 5)
+	 * filtered[0].value = 999 // Mutates draft.items[originalIndex]
+	 * ```
+	 *
+	 * **Transform operations** return base values (no draft tracking):
+	 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.
+	 *   Since the result structure differs from the original, tracking mutations
+	 *   back to specific draft indices would be impractical/impossible.
+	 *
+	 * **Primitive operations** return the native result directly:
+	 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.
+	 *
+	 * @param state - The proxy array state
+	 * @param method - The non-mutating method name
+	 * @param args - Arguments passed to the method
+	 * @returns Drafts for subset operations, base values for transforms, primitives otherwise
+	 */
+	function handleNonMutatingOperation(
+		state: ProxyArrayState,
+		method: NonMutatingArrayMethod,
+		args: any[]
+	) {
+		const source = latest(state)
+
+		// Methods that return arrays with selected items - need to return drafts
+		if (method === "filter") {
+			const predicate = args[0]
+			const result: any[] = []
+
+			// First pass: call predicate on base values to determine which items pass
+			for (let i = 0; i < source.length; i++) {
+				if (predicate(source[i], i, source)) {
+					// Only create draft for items that passed the predicate
+					result.push(state.draft_[i])
+				}
+			}
+
+			return result
+		}
+
+		if (FIND_METHODS.has(method)) {
+			const predicate = args[0]
+			const isForward = method === "find"
+			const step = isForward ? 1 : -1
+			const start = isForward ? 0 : source.length - 1
+
+			for (let i = start; i >= 0 && i < source.length; i += step) {
+				if (predicate(source[i], i, source)) {
+					return state.draft_[i]
+				}
+			}
+			return undefined
+		}
+
+		if (method === "slice") {
+			const rawStart = args[0] ?? 0
+			const rawEnd = args[1] ?? source.length
+
+			// Normalize negative indices
+			const start = normalizeSliceIndex(rawStart, source.length)
+			const end = normalizeSliceIndex(rawEnd, source.length)
+
+			const result: any[] = []
+
+			// Return drafts for items in the slice range
+			for (let i = start; i < end; i++) {
+				result.push(state.draft_[i])
+			}
+
+			return result
+		}
+
+		// For other methods, call on base array directly:
+		// - indexOf, includes, join, toString: Return primitives, no draft needed
+		// - concat, flat: Return NEW arrays (not subsets). Elements are base values.
+		//   This is intentional - concat/flat create new data structures rather than
+		//   selecting subsets of the original, making draft tracking impractical.
+		return source[method as keyof typeof Array.prototype](...args)
+	}
+
+	loadPlugin(PluginArrayMethods, {
+		createMethodInterceptor,
+		isArrayOperationMethod,
+		isMutatingArrayMethod
+	})
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/mapset.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/mapset.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/mapset.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,332 @@
+// types only!
+import {
+	ImmerState,
+	AnyMap,
+	AnySet,
+	MapState,
+	SetState,
+	DRAFT_STATE,
+	getCurrentScope,
+	latest,
+	isDraftable,
+	createProxy,
+	loadPlugin,
+	markChanged,
+	die,
+	ArchType,
+	each,
+	getValue,
+	PluginMapSet,
+	handleCrossReference
+} from "../internal"
+
+export function enableMapSet() {
+	class DraftMap extends Map {
+		[DRAFT_STATE]: MapState
+
+		constructor(target: AnyMap, parent?: ImmerState) {
+			super()
+			this[DRAFT_STATE] = {
+				type_: ArchType.Map,
+				parent_: parent,
+				scope_: parent ? parent.scope_ : getCurrentScope()!,
+				modified_: false,
+				finalized_: false,
+				copy_: undefined,
+				assigned_: undefined,
+				base_: target,
+				draft_: this as any,
+				isManual_: false,
+				revoked_: false,
+				callbacks_: []
+			}
+		}
+
+		get size(): number {
+			return latest(this[DRAFT_STATE]).size
+		}
+
+		has(key: any): boolean {
+			return latest(this[DRAFT_STATE]).has(key)
+		}
+
+		set(key: any, value: any) {
+			const state: MapState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			if (!latest(state).has(key) || latest(state).get(key) !== value) {
+				prepareMapCopy(state)
+				markChanged(state)
+				state.assigned_!.set(key, true)
+				state.copy_!.set(key, value)
+				state.assigned_!.set(key, true)
+				handleCrossReference(state, key, value)
+			}
+			return this
+		}
+
+		delete(key: any): boolean {
+			if (!this.has(key)) {
+				return false
+			}
+
+			const state: MapState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			prepareMapCopy(state)
+			markChanged(state)
+			if (state.base_.has(key)) {
+				state.assigned_!.set(key, false)
+			} else {
+				state.assigned_!.delete(key)
+			}
+			state.copy_!.delete(key)
+			return true
+		}
+
+		clear() {
+			const state: MapState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			if (latest(state).size) {
+				prepareMapCopy(state)
+				markChanged(state)
+				state.assigned_ = new Map()
+				each(state.base_, key => {
+					state.assigned_!.set(key, false)
+				})
+				state.copy_!.clear()
+			}
+		}
+
+		forEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {
+			const state: MapState = this[DRAFT_STATE]
+			latest(state).forEach((_value: any, key: any, _map: any) => {
+				cb.call(thisArg, this.get(key), key, this)
+			})
+		}
+
+		get(key: any): any {
+			const state: MapState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			const value = latest(state).get(key)
+			if (state.finalized_ || !isDraftable(value)) {
+				return value
+			}
+			if (value !== state.base_.get(key)) {
+				return value // either already drafted or reassigned
+			}
+			// despite what it looks, this creates a draft only once, see above condition
+			const draft = createProxy(state.scope_, value, state, key)
+			prepareMapCopy(state)
+			state.copy_!.set(key, draft)
+			return draft
+		}
+
+		keys(): IterableIterator<any> {
+			return latest(this[DRAFT_STATE]).keys()
+		}
+
+		values(): IterableIterator<any> {
+			const iterator = this.keys()
+			return {
+				[Symbol.iterator]: () => this.values(),
+				next: () => {
+					const r = iterator.next()
+					/* istanbul ignore next */
+					if (r.done) return r
+					const value = this.get(r.value)
+					return {
+						done: false,
+						value
+					}
+				}
+			} as any
+		}
+
+		entries(): IterableIterator<[any, any]> {
+			const iterator = this.keys()
+			return {
+				[Symbol.iterator]: () => this.entries(),
+				next: () => {
+					const r = iterator.next()
+					/* istanbul ignore next */
+					if (r.done) return r
+					const value = this.get(r.value)
+					return {
+						done: false,
+						value: [r.value, value]
+					}
+				}
+			} as any
+		}
+
+		[Symbol.iterator]() {
+			return this.entries()
+		}
+	}
+
+	function proxyMap_<T extends AnyMap>(
+		target: T,
+		parent?: ImmerState
+	): [T, MapState] {
+		// @ts-ignore
+		const map = new DraftMap(target, parent)
+		return [map as any, map[DRAFT_STATE]]
+	}
+
+	function prepareMapCopy(state: MapState) {
+		if (!state.copy_) {
+			state.assigned_ = new Map()
+			state.copy_ = new Map(state.base_)
+		}
+	}
+
+	class DraftSet extends Set {
+		[DRAFT_STATE]: SetState
+		constructor(target: AnySet, parent?: ImmerState) {
+			super()
+			this[DRAFT_STATE] = {
+				type_: ArchType.Set,
+				parent_: parent,
+				scope_: parent ? parent.scope_ : getCurrentScope()!,
+				modified_: false,
+				finalized_: false,
+				copy_: undefined,
+				base_: target,
+				draft_: this,
+				drafts_: new Map(),
+				revoked_: false,
+				isManual_: false,
+				assigned_: undefined,
+				callbacks_: []
+			}
+		}
+
+		get size(): number {
+			return latest(this[DRAFT_STATE]).size
+		}
+
+		has(value: any): boolean {
+			const state: SetState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			// bit of trickery here, to be able to recognize both the value, and the draft of its value
+			if (!state.copy_) {
+				return state.base_.has(value)
+			}
+			if (state.copy_.has(value)) return true
+			if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))
+				return true
+			return false
+		}
+
+		add(value: any): any {
+			const state: SetState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			if (!this.has(value)) {
+				prepareSetCopy(state)
+				markChanged(state)
+				state.copy_!.add(value)
+				handleCrossReference(state, value, value)
+			}
+			return this
+		}
+
+		delete(value: any): any {
+			if (!this.has(value)) {
+				return false
+			}
+
+			const state: SetState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			prepareSetCopy(state)
+			markChanged(state)
+			return (
+				state.copy_!.delete(value) ||
+				(state.drafts_.has(value)
+					? state.copy_!.delete(state.drafts_.get(value))
+					: /* istanbul ignore next */ false)
+			)
+		}
+
+		clear() {
+			const state: SetState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			if (latest(state).size) {
+				prepareSetCopy(state)
+				markChanged(state)
+				state.copy_!.clear()
+			}
+		}
+
+		values(): IterableIterator<any> {
+			const state: SetState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			prepareSetCopy(state)
+			return state.copy_!.values()
+		}
+
+		entries(): IterableIterator<[any, any]> {
+			const state: SetState = this[DRAFT_STATE]
+			assertUnrevoked(state)
+			prepareSetCopy(state)
+			return state.copy_!.entries()
+		}
+
+		keys(): IterableIterator<any> {
+			return this.values()
+		}
+
+		[Symbol.iterator]() {
+			return this.values()
+		}
+
+		forEach(cb: any, thisArg?: any) {
+			const iterator = this.values()
+			let result = iterator.next()
+			while (!result.done) {
+				cb.call(thisArg, result.value, result.value, this)
+				result = iterator.next()
+			}
+		}
+	}
+	function proxySet_<T extends AnySet>(
+		target: T,
+		parent?: ImmerState
+	): [T, SetState] {
+		// @ts-ignore
+		const set = new DraftSet(target, parent)
+		return [set as any, set[DRAFT_STATE]]
+	}
+
+	function prepareSetCopy(state: SetState) {
+		if (!state.copy_) {
+			// create drafts for all entries to preserve insertion order
+			state.copy_ = new Set()
+			state.base_.forEach(value => {
+				if (isDraftable(value)) {
+					const draft = createProxy(state.scope_, value, state, value)
+					state.drafts_.set(value, draft)
+					state.copy_!.add(draft)
+				} else {
+					state.copy_!.add(value)
+				}
+			})
+		}
+	}
+
+	function assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {
+		if (state.revoked_) die(3, JSON.stringify(latest(state)))
+	}
+
+	function fixSetContents(target: ImmerState) {
+		// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628
+		// To preserve insertion order in all cases we then clear the set
+		if (target.type_ === ArchType.Set && target.copy_) {
+			const copy = new Set(target.copy_)
+			target.copy_.clear()
+			copy.forEach(value => {
+				target.copy_!.add(getValue(value))
+			})
+		}
+	}
+
+	loadPlugin(PluginMapSet, {proxyMap_, proxySet_, fixSetContents})
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/patches.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/patches.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/plugins/patches.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,431 @@
+import {immerable} from "../immer"
+import {
+	ImmerState,
+	Patch,
+	SetState,
+	ProxyArrayState,
+	MapState,
+	ProxyObjectState,
+	PatchPath,
+	get,
+	each,
+	has,
+	getArchtype,
+	getPrototypeOf,
+	isSet,
+	isMap,
+	loadPlugin,
+	ArchType,
+	die,
+	isDraft,
+	isDraftable,
+	NOTHING,
+	errors,
+	DRAFT_STATE,
+	getProxyDraft,
+	ImmerScope,
+	isObjectish,
+	isFunction,
+	CONSTRUCTOR,
+	PluginPatches,
+	isArray,
+	PROTOTYPE
+} from "../internal"
+
+export function enablePatches() {
+	const errorOffset = 16
+	if (process.env.NODE_ENV !== "production") {
+		errors.push(
+			'Sets cannot have "replace" patches.',
+			function(op: string) {
+				return "Unsupported patch operation: " + op
+			},
+			function(path: string) {
+				return "Cannot apply patch, path doesn't resolve: " + path
+			},
+			"Patching reserved attributes like __proto__, prototype and constructor is not allowed"
+		)
+	}
+
+	function getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {
+		// Step 1: Check if state has a stored key
+		if (state.key_ !== undefined) {
+			// Step 2: Validate the key is still valid in parent
+
+			const parentCopy = state.parent_!.copy_ ?? state.parent_!.base_
+			const proxyDraft = getProxyDraft(get(parentCopy, state.key_!))
+			const valueAtKey = get(parentCopy, state.key_!)
+
+			if (valueAtKey === undefined) {
+				return null
+			}
+
+			// Check if the value at the key is still related to this draft
+			// It should be either the draft itself, the base, or the copy
+			if (
+				valueAtKey !== state.draft_ &&
+				valueAtKey !== state.base_ &&
+				valueAtKey !== state.copy_
+			) {
+				return null // Value was replaced with something else
+			}
+			if (proxyDraft != null && proxyDraft.base_ !== state.base_) {
+				return null // Different draft
+			}
+
+			// Step 3: Handle Set case specially
+			const isSet = state.parent_!.type_ === ArchType.Set
+			let key: string | number
+
+			if (isSet) {
+				// For Sets, find the index in the drafts_ map
+				const setParent = state.parent_ as SetState
+				key = Array.from(setParent.drafts_.keys()).indexOf(state.key_)
+			} else {
+				key = state.key_ as string | number
+			}
+
+			// Step 4: Validate key still exists in parent
+			if (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {
+				return null // Key deleted
+			}
+
+			// Step 5: Add key to path
+			path.push(key)
+		}
+
+		// Step 6: Recurse to parent if exists
+		if (state.parent_) {
+			return getPath(state.parent_, path)
+		}
+
+		// Step 7: At root - reverse path and validate
+		path.reverse()
+
+		try {
+			// Validate path can be resolved from ROOT
+			resolvePath(state.copy_, path)
+		} catch (e) {
+			return null // Path invalid
+		}
+
+		return path
+	}
+
+	// NEW: Add resolvePath helper function
+	function resolvePath(base: any, path: PatchPath): any {
+		let current = base
+		for (let i = 0; i < path.length - 1; i++) {
+			const key = path[i]
+			current = get(current, key)
+			if (!isObjectish(current) || current === null) {
+				throw new Error(`Cannot resolve path at '${path.join("/")}'`)
+			}
+		}
+		return current
+	}
+
+	const REPLACE = "replace"
+	const ADD = "add"
+	const REMOVE = "remove"
+
+	function generatePatches_(
+		state: ImmerState,
+		basePath: PatchPath,
+		scope: ImmerScope
+	): void {
+		if (state.scope_.processedForPatches_.has(state)) {
+			return
+		}
+
+		state.scope_.processedForPatches_.add(state)
+
+		const {patches_, inversePatches_} = scope
+
+		switch (state.type_) {
+			case ArchType.Object:
+			case ArchType.Map:
+				return generatePatchesFromAssigned(
+					state,
+					basePath,
+					patches_!,
+					inversePatches_!
+				)
+			case ArchType.Array:
+				return generateArrayPatches(
+					state,
+					basePath,
+					patches_!,
+					inversePatches_!
+				)
+			case ArchType.Set:
+				return generateSetPatches(
+					(state as any) as SetState,
+					basePath,
+					patches_!,
+					inversePatches_!
+				)
+		}
+	}
+
+	function generateArrayPatches(
+		state: ProxyArrayState,
+		basePath: PatchPath,
+		patches: Patch[],
+		inversePatches: Patch[]
+	) {
+		let {base_, assigned_} = state
+		let copy_ = state.copy_!
+
+		// Reduce complexity by ensuring `base` is never longer.
+		if (copy_.length < base_.length) {
+			// @ts-ignore
+			;[base_, copy_] = [copy_, base_]
+			;[patches, inversePatches] = [inversePatches, patches]
+		}
+
+		const allReassigned = state.allIndicesReassigned_ === true
+
+		// Process replaced indices.
+		for (let i = 0; i < base_.length; i++) {
+			const copiedItem = copy_[i]
+			const baseItem = base_[i]
+
+			const isAssigned = allReassigned || assigned_?.get(i.toString())
+			if (isAssigned && copiedItem !== baseItem) {
+				const childState = copiedItem?.[DRAFT_STATE]
+				if (childState && childState.modified_) {
+					// Skip - let the child generate its own patches
+					continue
+				}
+				const path = basePath.concat([i])
+				patches.push({
+					op: REPLACE,
+					path,
+					// Need to maybe clone it, as it can in fact be the original value
+					// due to the base/copy inversion at the start of this function
+					value: clonePatchValueIfNeeded(copiedItem)
+				})
+				inversePatches.push({
+					op: REPLACE,
+					path,
+					value: clonePatchValueIfNeeded(baseItem)
+				})
+			}
+		}
+
+		// Process added indices.
+		for (let i = base_.length; i < copy_.length; i++) {
+			const path = basePath.concat([i])
+			patches.push({
+				op: ADD,
+				path,
+				// Need to maybe clone it, as it can in fact be the original value
+				// due to the base/copy inversion at the start of this function
+				value: clonePatchValueIfNeeded(copy_[i])
+			})
+		}
+		for (let i = copy_.length - 1; base_.length <= i; --i) {
+			const path = basePath.concat([i])
+			inversePatches.push({
+				op: REMOVE,
+				path
+			})
+		}
+	}
+
+	// This is used for both Map objects and normal objects.
+	function generatePatchesFromAssigned(
+		state: MapState | ProxyObjectState,
+		basePath: PatchPath,
+		patches: Patch[],
+		inversePatches: Patch[]
+	) {
+		const {base_, copy_, type_} = state
+		each(state.assigned_!, (key, assignedValue) => {
+			const origValue = get(base_, key, type_)
+			const value = get(copy_!, key, type_)
+			const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD
+			if (origValue === value && op === REPLACE) return
+			const path = basePath.concat(key as any)
+			patches.push(
+				op === REMOVE
+					? {op, path}
+					: {op, path, value: clonePatchValueIfNeeded(value)}
+			)
+			inversePatches.push(
+				op === ADD
+					? {op: REMOVE, path}
+					: op === REMOVE
+					? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}
+					: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}
+			)
+		})
+	}
+
+	function generateSetPatches(
+		state: SetState,
+		basePath: PatchPath,
+		patches: Patch[],
+		inversePatches: Patch[]
+	) {
+		let {base_, copy_} = state
+
+		let i = 0
+		base_.forEach((value: any) => {
+			if (!copy_!.has(value)) {
+				const path = basePath.concat([i])
+				patches.push({
+					op: REMOVE,
+					path,
+					value
+				})
+				inversePatches.unshift({
+					op: ADD,
+					path,
+					value
+				})
+			}
+			i++
+		})
+		i = 0
+		copy_!.forEach((value: any) => {
+			if (!base_.has(value)) {
+				const path = basePath.concat([i])
+				patches.push({
+					op: ADD,
+					path,
+					value
+				})
+				inversePatches.unshift({
+					op: REMOVE,
+					path,
+					value
+				})
+			}
+			i++
+		})
+	}
+
+	function generateReplacementPatches_(
+		baseValue: any,
+		replacement: any,
+		scope: ImmerScope
+	): void {
+		const {patches_, inversePatches_} = scope
+		patches_!.push({
+			op: REPLACE,
+			path: [],
+			value: replacement === NOTHING ? undefined : replacement
+		})
+		inversePatches_!.push({
+			op: REPLACE,
+			path: [],
+			value: baseValue
+		})
+	}
+
+	function applyPatches_<T>(draft: T, patches: readonly Patch[]): T {
+		patches.forEach(patch => {
+			const {path, op} = patch
+
+			let base: any = draft
+			for (let i = 0; i < path.length - 1; i++) {
+				const parentType = getArchtype(base)
+				let p = path[i]
+				if (typeof p !== "string" && typeof p !== "number") {
+					p = "" + p
+				}
+
+				// See #738, avoid prototype pollution
+				if (
+					(parentType === ArchType.Object || parentType === ArchType.Array) &&
+					(p === "__proto__" || p === CONSTRUCTOR)
+				)
+					die(errorOffset + 3)
+				if (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)
+				base = get(base, p)
+				if (!isObjectish(base)) die(errorOffset + 2, path.join("/"))
+			}
+
+			const type = getArchtype(base)
+			const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411
+			const key = path[path.length - 1]
+			switch (op) {
+				case REPLACE:
+					switch (type) {
+						case ArchType.Map:
+							return base.set(key, value)
+						/* istanbul ignore next */
+						case ArchType.Set:
+							die(errorOffset)
+						default:
+							// if value is an object, then it's assigned by reference
+							// in the following add or remove ops, the value field inside the patch will also be modifyed
+							// so we use value from the cloned patch
+							// @ts-ignore
+							return (base[key] = value)
+					}
+				case ADD:
+					switch (type) {
+						case ArchType.Array:
+							return key === "-"
+								? base.push(value)
+								: base.splice(key as any, 0, value)
+						case ArchType.Map:
+							return base.set(key, value)
+						case ArchType.Set:
+							return base.add(value)
+						default:
+							return (base[key] = value)
+					}
+				case REMOVE:
+					switch (type) {
+						case ArchType.Array:
+							return base.splice(key as any, 1)
+						case ArchType.Map:
+							return base.delete(key)
+						case ArchType.Set:
+							return base.delete(patch.value)
+						default:
+							return delete base[key]
+					}
+				default:
+					die(errorOffset + 1, op)
+			}
+		})
+
+		return draft
+	}
+
+	// optimize: this is quite a performance hit, can we detect intelligently when it is needed?
+	// E.g. auto-draft when new objects from outside are assigned and modified?
+	// (See failing test when deepClone just returns obj)
+	function deepClonePatchValue<T>(obj: T): T
+	function deepClonePatchValue(obj: any) {
+		if (!isDraftable(obj)) return obj
+		if (isArray(obj)) return obj.map(deepClonePatchValue)
+		if (isMap(obj))
+			return new Map(
+				Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
+			)
+		if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))
+		const cloned = Object.create(getPrototypeOf(obj))
+		for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])
+		if (has(obj, immerable)) cloned[immerable] = obj[immerable]
+		return cloned
+	}
+
+	function clonePatchValueIfNeeded<T>(obj: T): T {
+		if (isDraft(obj)) {
+			return deepClonePatchValue(obj)
+		} else return obj
+	}
+
+	loadPlugin(PluginPatches, {
+		applyPatches_,
+		generatePatches_,
+		generateReplacementPatches_,
+		getPath
+	})
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/types/globals.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/types/globals.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/types/globals.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+declare const __DEV__: boolean
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/types/index.js.flow
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/types/index.js.flow	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/types/index.js.flow	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,112 @@
+// @flow
+
+export interface Patch {
+	op: "replace" | "remove" | "add";
+	path: (string | number)[];
+	value?: any;
+}
+
+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void
+
+type Base = {...} | Array<any>
+interface IProduce {
+	/**
+	 * Immer takes a state, and runs a function against it.
+	 * That function can freely mutate the state, as it will create copies-on-write.
+	 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.
+	 *
+	 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe
+	 * any time it is called with the current state.
+	 *
+	 * @param currentState - the state to start with
+	 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified
+	 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined
+	 * @returns The next state: a new state, or the current state if nothing was modified
+	 */
+	<S: Base>(
+		currentState: S,
+		recipe: (draftState: S) => S | void,
+		patchListener?: PatchListener
+	): S;
+	// curried invocations with initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,
+		initialState: S
+	): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => S;
+	// curried invocations without initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void
+	): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S;
+}
+
+interface IProduceWithPatches {
+        /**
+         * Like `produce`, but instead of just returning the new state,
+         * a tuple is returned with [nextState, patches, inversePatches]
+         *
+         * Like produce, this function supports currying
+         */
+	<S: Base>(
+		currentState: S,
+		recipe: (draftState: S) => S | void
+	): [S, Patch[], Patch[]];
+	// curried invocations with initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,
+		initialState: S
+	): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => [S, Patch[], Patch[]];
+	// curried invocations without initial state
+	<S: Base, A = void, B = void, C = void>(
+		recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void
+	): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => [S, Patch[], Patch[]];
+}
+
+declare export var produce: IProduce
+
+declare export var produceWithPatches: IProduceWithPatches
+
+declare export var nothing: typeof undefined
+
+declare export var immerable: Symbol
+
+/**
+ * Automatically freezes any state trees generated by immer.
+ * This protects against accidental modifications of the state tree outside of an immer function.
+ * This comes with a performance impact, so it is recommended to disable this option in production.
+ * By default it is turned on during local development, and turned off in production.
+ */
+declare export function setAutoFreeze(autoFreeze: boolean): void
+
+/**
+ * Pass false to disable strict shallow copy.
+ *
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
+ */
+declare export function setUseStrictShallowCopy(useStrictShallowCopy: boolean): void
+
+declare export function applyPatches<S>(state: S, patches: Patch[]): S
+
+declare export function original<S>(value: S): S
+
+declare export function current<S>(value: S): S
+
+declare export function isDraft(value: any): boolean
+
+/**
+ * Creates a mutable draft from an (immutable) object / array.
+ * The draft can be modified until `finishDraft` is called
+ */
+declare export function createDraft<T>(base: T): T
+
+/**
+ * Given a draft that was created using `createDraft`,
+ * finalizes the draft into a new immutable object.
+ * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.
+ */
+declare export function finishDraft<T>(base: T, listener?: PatchListener): T
+
+declare export function enableMapSet(): void
+declare export function enablePatches(): void
+declare export function enableArrayMethods(): void
+
+declare export function freeze<T>(obj: T, freeze?: boolean): T
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/types/types-external.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/types/types-external.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/types/types-external.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,251 @@
+import {NOTHING} from "../internal"
+
+type AnyFunc = (...args: any[]) => any
+
+type PrimitiveType = number | string | boolean
+
+/** Object types that should never be mapped */
+type AtomicObject = Function | Promise<any> | Date | RegExp
+
+/**
+ * If the lib "ES2015.Collection" is not included in tsconfig.json,
+ * types like ReadonlyArray, WeakMap etc. fall back to `any` (specified nowhere)
+ * or `{}` (from the node types), in both cases entering an infinite recursion in
+ * pattern matching type mappings
+ * This type can be used to cast these types to `void` in these cases.
+ */
+export type IfAvailable<T, Fallback = void> =
+	// fallback if any
+	true | false extends (T extends never
+	? true
+	: false)
+		? Fallback // fallback if empty type
+		: keyof T extends never
+		? Fallback // original type
+		: T
+
+/**
+ * These should also never be mapped but must be tested after regular Map and
+ * Set
+ */
+type WeakReferences = IfAvailable<WeakMap<any, any>> | IfAvailable<WeakSet<any>>
+
+export type WritableDraft<T> = T extends any[]
+	? number extends T["length"]
+		? Draft<T[number]>[]
+		: WritableNonArrayDraft<T>
+	: WritableNonArrayDraft<T>
+
+type WritableNonArrayDraft<T> = {
+	-readonly [K in keyof T]: T[K] extends infer V
+		? V extends object
+			? Draft<V>
+			: V
+		: never
+}
+
+/** Convert a readonly type into a mutable type, if possible */
+export type Draft<T> = T extends PrimitiveType
+	? T
+	: T extends AtomicObject
+	? T
+	: T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap
+	? Map<Draft<K>, Draft<V>>
+	: T extends ReadonlySet<infer V> // Set extends ReadonlySet
+	? Set<Draft<V>>
+	: T extends WeakReferences
+	? T
+	: T extends object
+	? WritableDraft<T>
+	: T
+
+/** Convert a mutable type into a readonly type */
+export type Immutable<T> = T extends PrimitiveType
+	? T
+	: T extends AtomicObject
+	? T
+	: T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap
+	? ReadonlyMap<Immutable<K>, Immutable<V>>
+	: T extends ReadonlySet<infer V> // Set extends ReadonlySet
+	? ReadonlySet<Immutable<V>>
+	: T extends WeakReferences
+	? T
+	: T extends object
+	? {readonly [K in keyof T]: Immutable<T[K]>}
+	: T
+
+export interface Patch {
+	op: "replace" | "remove" | "add"
+	path: (string | number)[]
+	value?: any
+}
+
+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void
+
+/** Converts `nothing` into `undefined` */
+type FromNothing<T> = T extends typeof NOTHING ? undefined : T
+
+/** The inferred return type of `produce` */
+export type Produced<Base, Return> = Return extends void
+	? Base
+	: FromNothing<Return>
+
+/**
+ * Utility types
+ */
+type PatchesTuple<T> = readonly [T, Patch[], Patch[]]
+
+type ValidRecipeReturnType<State> =
+	| State
+	| void
+	| undefined
+	| (State extends undefined ? typeof NOTHING : never)
+
+type ReturnTypeWithPatchesIfNeeded<
+	State,
+	UsePatches extends boolean
+> = UsePatches extends true ? PatchesTuple<State> : State
+
+/**
+ * Core Producer inference
+ */
+type InferRecipeFromCurried<Curried> = Curried extends (
+	base: infer State,
+	...rest: infer Args
+) => any // extra assertion to make sure this is a proper curried function (state, args) => state
+	? ReturnType<Curried> extends State
+		? (
+				draft: Draft<State>,
+				...rest: Args
+		  ) => ValidRecipeReturnType<Draft<State>>
+		: never
+	: never
+
+type InferInitialStateFromCurried<Curried> = Curried extends (
+	base: infer State,
+	...rest: any[]
+) => any // extra assertion to make sure this is a proper curried function (state, args) => state
+	? State
+	: never
+
+type InferCurriedFromRecipe<
+	Recipe,
+	UsePatches extends boolean
+> = Recipe extends (draft: infer DraftState, ...args: infer RestArgs) => any // verify return type
+	? ReturnType<Recipe> extends ValidRecipeReturnType<DraftState>
+		? (
+				base: Immutable<DraftState>,
+				...args: RestArgs
+		  ) => ReturnTypeWithPatchesIfNeeded<DraftState, UsePatches> // N.b. we return mutable draftstate, in case the recipe's first arg isn't read only, and that isn't expected as output either
+		: never // incorrect return type
+	: never // not a function
+
+type InferCurriedFromInitialStateAndRecipe<
+	State,
+	Recipe,
+	UsePatches extends boolean
+> = Recipe extends (
+	draft: Draft<State>,
+	...rest: infer RestArgs
+) => ValidRecipeReturnType<State>
+	? (
+			base?: State | undefined,
+			...args: RestArgs
+	  ) => ReturnTypeWithPatchesIfNeeded<State, UsePatches>
+	: never // recipe doesn't match initial state
+
+/**
+ * The `produce` function takes a value and a "recipe function" (whose
+ * return value often depends on the base state). The recipe function is
+ * free to mutate its first argument however it wants. All mutations are
+ * only ever applied to a __copy__ of the base state.
+ *
+ * Pass only a function to create a "curried producer" which relieves you
+ * from passing the recipe function every time.
+ *
+ * Only plain objects and arrays are made mutable. All other objects are
+ * considered uncopyable.
+ *
+ * Note: This function is __bound__ to its `Immer` instance.
+ *
+ * @param {any} base - the initial state
+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
+ * @returns {any} a new state, or the initial state if nothing was modified
+ */
+export interface IProduce {
+	/** Curried producer that infers the recipe from the curried output function (e.g. when passing to setState) */
+	<Curried>(
+		recipe: InferRecipeFromCurried<Curried>,
+		initialState?: InferInitialStateFromCurried<Curried>
+	): Curried
+
+	/** Curried producer that infers curried from the recipe  */
+	<Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<
+		Recipe,
+		false
+	>
+
+	/** Curried producer that infers curried from the State generic, which is explicitly passed in.  */
+	<State>(
+		recipe: (
+			state: Draft<State>,
+			initialState: State
+		) => ValidRecipeReturnType<State>
+	): (state?: State) => State
+	<State, Args extends any[]>(
+		recipe: (
+			state: Draft<State>,
+			...args: Args
+		) => ValidRecipeReturnType<State>,
+		initialState: State
+	): (state?: State, ...args: Args) => State
+	<State>(recipe: (state: Draft<State>) => ValidRecipeReturnType<State>): (
+		state: State
+	) => State
+	<State, Args extends any[]>(
+		recipe: (state: Draft<State>, ...args: Args) => ValidRecipeReturnType<State>
+	): (state: State, ...args: Args) => State
+
+	/** Curried producer with initial state, infers recipe from initial state */
+	<State, Recipe extends Function>(
+		recipe: Recipe,
+		initialState: State
+	): InferCurriedFromInitialStateAndRecipe<State, Recipe, false>
+
+	/** Normal producer */
+	<Base, D = Draft<Base>>( // By using a default inferred D, rather than Draft<Base> in the recipe, we can override it.
+		base: Base,
+		recipe: (draft: D) => ValidRecipeReturnType<D>,
+		listener?: PatchListener
+	): Base
+}
+
+/**
+ * Like `produce`, but instead of just returning the new state,
+ * a tuple is returned with [nextState, patches, inversePatches]
+ *
+ * Like produce, this function supports currying
+ */
+export interface IProduceWithPatches {
+	// Types copied from IProduce, wrapped with PatchesTuple
+	<Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<Recipe, true>
+	<State, Recipe extends Function>(
+		recipe: Recipe,
+		initialState: State
+	): InferCurriedFromInitialStateAndRecipe<State, Recipe, true>
+	<Base, D = Draft<Base>>(
+		base: Base,
+		recipe: (draft: D) => ValidRecipeReturnType<D>,
+		listener?: PatchListener
+	): PatchesTuple<Base>
+}
+
+/**
+ * The type for `recipe function`
+ */
+export type Producer<T> = (draft: Draft<T>) => ValidRecipeReturnType<Draft<T>>
+
+// Fixes #507: bili doesn't export the types of this file if there is no actual source in it..
+// hopefully it get's tree-shaken away for everyone :)
+export function never_used() {}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/types/types-internal.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/types/types-internal.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/types/types-internal.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,55 @@
+import {
+	SetState,
+	ImmerScope,
+	ProxyObjectState,
+	ProxyArrayState,
+	MapState,
+	DRAFT_STATE,
+	Patch,
+	PatchPath
+} from "../internal"
+
+export type Objectish = AnyObject | AnyArray | AnyMap | AnySet
+export type ObjectishNoSet = AnyObject | AnyArray | AnyMap
+
+export type AnyObject = {[key: string]: any}
+export type AnyArray = Array<any>
+export type AnySet = Set<any>
+export type AnyMap = Map<any, any>
+
+export const enum ArchType {
+	Object,
+	Array,
+	Map,
+	Set
+}
+
+export interface ImmerBaseState {
+	parent_?: ImmerState
+	scope_: ImmerScope
+	modified_: boolean
+	finalized_: boolean
+	isManual_: boolean
+	assigned_: Map<any, boolean> | undefined
+	key_?: string | number | symbol
+	callbacks_: ((scope: ImmerScope) => void)[]
+	draftLocations_?: Map<any, (string | number | symbol)[]>
+}
+
+export type ImmerState =
+	| ProxyObjectState
+	| ProxyArrayState
+	| MapState
+	| SetState
+
+// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)
+export type Drafted<Base = any, T extends ImmerState = ImmerState> = {
+	[DRAFT_STATE]: T
+} & Base
+
+export type GeneratePatches = (
+	state: ImmerState,
+	basePath: PatchPath,
+	patches: Patch[],
+	inversePatches: Patch[]
+) => void
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/common.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/common.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/common.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,286 @@
+import {
+	DRAFT_STATE,
+	DRAFTABLE,
+	Objectish,
+	Drafted,
+	AnyObject,
+	AnyMap,
+	AnySet,
+	ImmerState,
+	ArchType,
+	die,
+	StrictMode
+} from "../internal"
+
+const O = Object
+
+export const getPrototypeOf = O.getPrototypeOf
+
+export const CONSTRUCTOR = "constructor"
+export const PROTOTYPE = "prototype"
+
+export const CONFIGURABLE = "configurable"
+export const ENUMERABLE = "enumerable"
+export const WRITABLE = "writable"
+export const VALUE = "value"
+
+/** Returns true if the given value is an Immer draft */
+/*#__PURE__*/
+export let isDraft = (value: any): boolean => !!value && !!value[DRAFT_STATE]
+
+/** Returns true if the given value can be drafted by Immer */
+/*#__PURE__*/
+export function isDraftable(value: any): boolean {
+	if (!value) return false
+	return (
+		isPlainObject(value) ||
+		isArray(value) ||
+		!!value[DRAFTABLE] ||
+		!!value[CONSTRUCTOR]?.[DRAFTABLE] ||
+		isMap(value) ||
+		isSet(value)
+	)
+}
+
+const objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString()
+const cachedCtorStrings = new WeakMap()
+/*#__PURE__*/
+export function isPlainObject(value: any): boolean {
+	if (!value || !isObjectish(value)) return false
+	const proto = getPrototypeOf(value)
+	if (proto === null || proto === O[PROTOTYPE]) return true
+
+	const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR]
+	if (Ctor === Object) return true
+
+	if (!isFunction(Ctor)) return false
+
+	let ctorString = cachedCtorStrings.get(Ctor)
+	if (ctorString === undefined) {
+		ctorString = Function.toString.call(Ctor)
+		cachedCtorStrings.set(Ctor, ctorString)
+	}
+
+	return ctorString === objectCtorString
+}
+
+/** Get the underlying object that is represented by the given draft */
+/*#__PURE__*/
+export function original<T>(value: T): T | undefined
+export function original(value: Drafted<any>): any {
+	if (!isDraft(value)) die(15, value)
+	return value[DRAFT_STATE].base_
+}
+
+/**
+ * Each iterates a map, set or array.
+ * Or, if any other kind of object, all of its own properties.
+ *
+ * @param obj The object to iterate over
+ * @param iter The iterator function
+ * @param strict When true (default), includes symbols and non-enumerable properties.
+ *               When false, uses looseiteration over only enumerable string properties.
+ */
+export function each<T extends Objectish>(
+	obj: T,
+	iter: (key: string | number, value: any, source: T) => void,
+	strict?: boolean
+): void
+export function each(obj: any, iter: any, strict: boolean = true) {
+	if (getArchtype(obj) === ArchType.Object) {
+		// If strict, we do a full iteration including symbols and non-enumerable properties
+		// Otherwise, we only iterate enumerable string properties for performance
+		const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj)
+		keys.forEach(key => {
+			iter(key, obj[key], obj)
+		})
+	} else {
+		obj.forEach((entry: any, index: any) => iter(index, entry, obj))
+	}
+}
+
+/*#__PURE__*/
+export function getArchtype(thing: any): ArchType {
+	const state: undefined | ImmerState = thing[DRAFT_STATE]
+	return state
+		? state.type_
+		: isArray(thing)
+		? ArchType.Array
+		: isMap(thing)
+		? ArchType.Map
+		: isSet(thing)
+		? ArchType.Set
+		: ArchType.Object
+}
+
+/*#__PURE__*/
+export let has = (
+	thing: any,
+	prop: PropertyKey,
+	type = getArchtype(thing)
+): boolean =>
+	type === ArchType.Map
+		? thing.has(prop)
+		: O[PROTOTYPE].hasOwnProperty.call(thing, prop)
+
+/*#__PURE__*/
+export let get = (
+	thing: AnyMap | AnyObject,
+	prop: PropertyKey,
+	type = getArchtype(thing)
+): any =>
+	// @ts-ignore
+	type === ArchType.Map ? thing.get(prop) : thing[prop]
+
+/*#__PURE__*/
+export let set = (
+	thing: any,
+	propOrOldValue: PropertyKey,
+	value: any,
+	type = getArchtype(thing)
+) => {
+	if (type === ArchType.Map) thing.set(propOrOldValue, value)
+	else if (type === ArchType.Set) {
+		thing.add(value)
+	} else thing[propOrOldValue] = value
+}
+
+/*#__PURE__*/
+export function is(x: any, y: any): boolean {
+	// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
+	if (x === y) {
+		return x !== 0 || 1 / x === 1 / y
+	} else {
+		return x !== x && y !== y
+	}
+}
+
+export let isArray = Array.isArray
+
+/*#__PURE__*/
+export let isMap = (target: any): target is AnyMap => target instanceof Map
+
+/*#__PURE__*/
+export let isSet = (target: any): target is AnySet => target instanceof Set
+
+export let isObjectish = (target: any) => typeof target === "object"
+
+export let isFunction = (target: any): target is Function =>
+	typeof target === "function"
+
+export let isBoolean = (target: any): target is boolean =>
+	typeof target === "boolean"
+
+export function isArrayIndex(value: string | number): value is number | string {
+	const n = +value
+	return Number.isInteger(n) && String(n) === value
+}
+
+export let getProxyDraft = <T extends any>(value: T): ImmerState | null => {
+	if (!isObjectish(value)) return null
+	return (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]
+}
+
+/*#__PURE__*/
+export let latest = (state: ImmerState): any => state.copy_ || state.base_
+
+export let getValue = <T extends object>(value: T): T => {
+	const proxyDraft = getProxyDraft(value)
+	return proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value
+}
+
+export let getFinalValue = (state: ImmerState): any =>
+	state.modified_ ? state.copy_ : state.base_
+
+/*#__PURE__*/
+export function shallowCopy(base: any, strict: StrictMode) {
+	if (isMap(base)) {
+		return new Map(base)
+	}
+	if (isSet(base)) {
+		return new Set(base)
+	}
+	if (isArray(base)) return Array[PROTOTYPE].slice.call(base)
+
+	const isPlain = isPlainObject(base)
+
+	if (strict === true || (strict === "class_only" && !isPlain)) {
+		// Perform a strict copy
+		const descriptors = O.getOwnPropertyDescriptors(base)
+		delete descriptors[DRAFT_STATE as any]
+		let keys = Reflect.ownKeys(descriptors)
+		for (let i = 0; i < keys.length; i++) {
+			const key: any = keys[i]
+			const desc = descriptors[key]
+			if (desc[WRITABLE] === false) {
+				desc[WRITABLE] = true
+				desc[CONFIGURABLE] = true
+			}
+			// like object.assign, we will read any _own_, get/set accessors. This helps in dealing
+			// with libraries that trap values, like mobx or vue
+			// unlike object.assign, non-enumerables will be copied as well
+			if (desc.get || desc.set)
+				descriptors[key] = {
+					[CONFIGURABLE]: true,
+					[WRITABLE]: true, // could live with !!desc.set as well here...
+					[ENUMERABLE]: desc[ENUMERABLE],
+					[VALUE]: base[key]
+				}
+		}
+		return O.create(getPrototypeOf(base), descriptors)
+	} else {
+		// perform a sloppy copy
+		const proto = getPrototypeOf(base)
+		if (proto !== null && isPlain) {
+			return {...base} // assumption: better inner class optimization than the assign below
+		}
+		const obj = O.create(proto)
+		return O.assign(obj, base)
+	}
+}
+
+/**
+ * Freezes draftable objects. Returns the original object.
+ * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.
+ *
+ * @param obj
+ * @param deep
+ */
+export function freeze<T>(obj: T, deep?: boolean): T
+export function freeze<T>(obj: any, deep: boolean = false): T {
+	if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj
+	if (getArchtype(obj) > 1 /* Map or Set */) {
+		O.defineProperties(obj, {
+			set: dontMutateMethodOverride,
+			add: dontMutateMethodOverride,
+			clear: dontMutateMethodOverride,
+			delete: dontMutateMethodOverride
+		})
+	}
+	O.freeze(obj)
+	if (deep)
+		// See #590, don't recurse into non-enumerable / Symbol properties when freezing
+		// So use Object.values (only string-like, enumerables) instead of each()
+		each(
+			obj,
+			(_key, value) => {
+				freeze(value, true)
+			},
+			false
+		)
+	return obj
+}
+
+function dontMutateFrozenCollections() {
+	die(2)
+}
+
+const dontMutateMethodOverride = {
+	[VALUE]: dontMutateFrozenCollections
+}
+
+export function isFrozen(obj: any): boolean {
+	// Fast path: primitives and null/undefined are always "frozen"
+	if (obj === null || !isObjectish(obj)) return true
+	return O.isFrozen(obj)
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/env.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/env.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/env.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,18 @@
+// Should be no imports here!
+
+/**
+ * The sentinel value returned by producers to replace the draft with undefined.
+ */
+export const NOTHING: unique symbol = Symbol.for("immer-nothing")
+
+/**
+ * To let Immer treat your class instances as plain immutable objects
+ * (albeit with a custom prototype), you must define either an instance property
+ * or a static property on each of your custom classes.
+ *
+ * Otherwise, your class instance will never be drafted, which means it won't be
+ * safe to mutate in a produce callback.
+ */
+export const DRAFTABLE: unique symbol = Symbol.for("immer-draftable")
+
+export const DRAFT_STATE: unique symbol = Symbol.for("immer-state")
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/errors.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/errors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/errors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,50 @@
+import {isFunction} from "../internal"
+
+export const errors =
+	process.env.NODE_ENV !== "production"
+		? [
+				// All error codes, starting by 0:
+				function(plugin: string) {
+					return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`
+				},
+				function(thing: string) {
+					return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`
+				},
+				"This object has been frozen and should not be mutated",
+				function(data: any) {
+					return (
+						"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +
+						data
+					)
+				},
+				"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
+				"Immer forbids circular references",
+				"The first or second argument to `produce` must be a function",
+				"The third argument to `produce` must be a function or undefined",
+				"First argument to `createDraft` must be a plain object, an array, or an immerable object",
+				"First argument to `finishDraft` must be a draft returned by `createDraft`",
+				function(thing: string) {
+					return `'current' expects a draft, got: ${thing}`
+				},
+				"Object.defineProperty() cannot be used on an Immer draft",
+				"Object.setPrototypeOf() cannot be used on an Immer draft",
+				"Immer only supports deleting array indices",
+				"Immer only supports setting array indices and the 'length' property",
+				function(thing: string) {
+					return `'original' expects a draft, got: ${thing}`
+				}
+				// Note: if more errors are added, the errorOffset in Patches.ts should be increased
+				// See Patches.ts for additional errors
+		  ]
+		: []
+
+export function die(error: number, ...args: any[]): never {
+	if (process.env.NODE_ENV !== "production") {
+		const e = errors[error]
+		const msg = isFunction(e) ? e.apply(null, args as any) : e
+		throw new Error(`[Immer] ${msg}`)
+	}
+	throw new Error(
+		`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
+	)
+}
Index: node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/plugins.ts
===================================================================
--- node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/plugins.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/node_modules/immer/src/utils/plugins.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,99 @@
+import {
+	ImmerState,
+	Patch,
+	Drafted,
+	ImmerBaseState,
+	AnyMap,
+	AnySet,
+	ArchType,
+	die,
+	ImmerScope,
+	ProxyArrayState
+} from "../internal"
+
+export const PluginMapSet = "MapSet"
+export const PluginPatches = "Patches"
+export const PluginArrayMethods = "ArrayMethods"
+
+export type PatchesPlugin = {
+	generatePatches_(
+		state: ImmerState,
+		basePath: PatchPath,
+		rootScope: ImmerScope
+	): void
+	generateReplacementPatches_(
+		base: any,
+		replacement: any,
+		rootScope: ImmerScope
+	): void
+	applyPatches_<T>(draft: T, patches: readonly Patch[]): T
+	getPath: (state: ImmerState) => PatchPath | null
+}
+
+export type MapSetPlugin = {
+	proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): [T, ImmerState]
+	proxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]
+	fixSetContents: (state: ImmerState) => void
+}
+
+export type ArrayMethodsPlugin = {
+	createMethodInterceptor: (state: ProxyArrayState, method: string) => Function
+	isArrayOperationMethod: (method: string) => boolean
+	isMutatingArrayMethod: (method: string) => boolean
+}
+
+/** Plugin utilities */
+const plugins: {
+	Patches?: PatchesPlugin
+	MapSet?: MapSetPlugin
+	ArrayMethods?: ArrayMethodsPlugin
+} = {}
+
+type Plugins = typeof plugins
+
+export function getPlugin<K extends keyof Plugins>(
+	pluginKey: K
+): Exclude<Plugins[K], undefined> {
+	const plugin = plugins[pluginKey]
+	if (!plugin) {
+		die(0, pluginKey)
+	}
+	// @ts-ignore
+	return plugin
+}
+
+export let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>
+	!!plugins[pluginKey]
+
+export let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {
+	delete plugins[pluginKey]
+}
+
+export function loadPlugin<K extends keyof Plugins>(
+	pluginKey: K,
+	implementation: Plugins[K]
+): void {
+	if (!plugins[pluginKey]) plugins[pluginKey] = implementation
+}
+/** Map / Set plugin */
+
+export interface MapState extends ImmerBaseState {
+	type_: ArchType.Map
+	copy_: AnyMap | undefined
+	base_: AnyMap
+	revoked_: boolean
+	draft_: Drafted<AnyMap, MapState>
+}
+
+export interface SetState extends ImmerBaseState {
+	type_: ArchType.Set
+	copy_: AnySet | undefined
+	base_: AnySet
+	drafts_: Map<any, Drafted> // maps the original value to the draft value in the new set
+	revoked_: boolean
+	draft_: Drafted<AnySet, SetState>
+}
+
+/** Patches plugin */
+
+export type PatchPath = (string | number)[]
Index: node_modules/@reduxjs/toolkit/package.json
===================================================================
--- node_modules/@reduxjs/toolkit/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,286 @@
+{
+  "name": "@reduxjs/toolkit",
+  "version": "2.11.2",
+  "description": "The official, opinionated, batteries-included toolset for efficient Redux development",
+  "author": "Mark Erikson <mark@isquaredsoftware.com>",
+  "license": "MIT",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/reduxjs/redux-toolkit.git"
+  },
+  "keywords": [
+    "redux",
+    "react",
+    "starter",
+    "toolkit",
+    "reducer",
+    "slice",
+    "immer",
+    "immutable",
+    "redux-toolkit"
+  ],
+  "publishConfig": {
+    "access": "public"
+  },
+  "module": "dist/redux-toolkit.legacy-esm.js",
+  "main": "dist/cjs/index.js",
+  "types": "dist/index.d.ts",
+  "react-native": "dist/redux-toolkit.legacy-esm.js",
+  "unpkg": "dist/redux-toolkit.browser.mjs",
+  "exports": {
+    "./package.json": "./package.json",
+    ".": {
+      "module-sync": {
+        "types": "./dist/index.d.mts",
+        "default": "./dist/redux-toolkit.modern.mjs"
+      },
+      "module": {
+        "types": "./dist/index.d.mts",
+        "default": "./dist/redux-toolkit.modern.mjs"
+      },
+      "react-native": {
+        "import": {
+          "types": "./dist/index.d.mts",
+          "default": "./dist/redux-toolkit.modern.mjs"
+        },
+        "default": {
+          "types": "./dist/index.d.ts",
+          "default": "./dist/cjs/index.js"
+        }
+      },
+      "browser": {
+        "import": {
+          "types": "./dist/index.d.mts",
+          "default": "./dist/redux-toolkit.browser.mjs"
+        },
+        "default": {
+          "types": "./dist/index.d.ts",
+          "default": "./dist/cjs/index.js"
+        }
+      },
+      "import": {
+        "types": "./dist/index.d.mts",
+        "default": "./dist/redux-toolkit.modern.mjs"
+      },
+      "default": {
+        "types": "./dist/index.d.ts",
+        "default": "./dist/cjs/index.js"
+      }
+    },
+    "./react": {
+      "module-sync": {
+        "types": "./dist/react/index.d.mts",
+        "default": "./dist/react/redux-toolkit-react.modern.mjs"
+      },
+      "module": {
+        "types": "./dist/react/index.d.mts",
+        "default": "./dist/react/redux-toolkit-react.modern.mjs"
+      },
+      "react-native": {
+        "import": {
+          "types": "./dist/react/index.d.mts",
+          "default": "./dist/react/redux-toolkit-react.modern.mjs"
+        },
+        "default": {
+          "types": "./dist/react/index.d.ts",
+          "default": "./dist/react/cjs/index.js"
+        }
+      },
+      "browser": {
+        "import": {
+          "types": "./dist/react/index.d.mts",
+          "default": "./dist/react/redux-toolkit-react.browser.mjs"
+        },
+        "default": {
+          "types": "./dist/react/index.d.ts",
+          "default": "./dist/react/cjs/index.js"
+        }
+      },
+      "import": {
+        "types": "./dist/react/index.d.mts",
+        "default": "./dist/react/redux-toolkit-react.modern.mjs"
+      },
+      "default": {
+        "types": "./dist/react/index.d.ts",
+        "default": "./dist/react/cjs/index.js"
+      }
+    },
+    "./query": {
+      "module-sync": {
+        "types": "./dist/query/index.d.mts",
+        "default": "./dist/query/rtk-query.modern.mjs"
+      },
+      "module": {
+        "types": "./dist/query/index.d.mts",
+        "default": "./dist/query/rtk-query.modern.mjs"
+      },
+      "react-native": {
+        "import": {
+          "types": "./dist/query/index.d.mts",
+          "default": "./dist/query/rtk-query.modern.mjs"
+        },
+        "default": {
+          "types": "./dist/query/index.d.ts",
+          "default": "./dist/query/cjs/index.js"
+        }
+      },
+      "browser": {
+        "import": {
+          "types": "./dist/query/index.d.mts",
+          "default": "./dist/query/rtk-query.browser.mjs"
+        },
+        "default": {
+          "types": "./dist/query/index.d.ts",
+          "default": "./dist/query/cjs/index.js"
+        }
+      },
+      "import": {
+        "types": "./dist/query/index.d.mts",
+        "default": "./dist/query/rtk-query.modern.mjs"
+      },
+      "default": {
+        "types": "./dist/query/index.d.ts",
+        "default": "./dist/query/cjs/index.js"
+      }
+    },
+    "./query/react": {
+      "module-sync": {
+        "types": "./dist/query/react/index.d.mts",
+        "default": "./dist/query/react/rtk-query-react.modern.mjs"
+      },
+      "module": {
+        "types": "./dist/query/react/index.d.mts",
+        "default": "./dist/query/react/rtk-query-react.modern.mjs"
+      },
+      "react-native": {
+        "import": {
+          "types": "./dist/query/react/index.d.mts",
+          "default": "./dist/query/react/rtk-query-react.modern.mjs"
+        },
+        "default": {
+          "types": "./dist/query/react/index.d.ts",
+          "default": "./dist/query/react/cjs/index.js"
+        }
+      },
+      "browser": {
+        "import": {
+          "types": "./dist/query/react/index.d.mts",
+          "default": "./dist/query/react/rtk-query-react.browser.mjs"
+        },
+        "default": {
+          "types": "./dist/query/react/index.d.ts",
+          "default": "./dist/query/react/cjs/index.js"
+        }
+      },
+      "import": {
+        "types": "./dist/query/react/index.d.mts",
+        "default": "./dist/query/react/rtk-query-react.modern.mjs"
+      },
+      "default": {
+        "types": "./dist/query/react/index.d.ts",
+        "default": "./dist/query/react/cjs/index.js"
+      }
+    }
+  },
+  "devDependencies": {
+    "@arethetypeswrong/cli": "^0.13.5",
+    "@babel/core": "^7.24.8",
+    "@babel/helper-module-imports": "^7.24.7",
+    "@microsoft/api-extractor": "^7.13.2",
+    "@phryneas/ts-version": "^1.0.2",
+    "@size-limit/file": "^11.0.1",
+    "@size-limit/webpack": "^11.0.1",
+    "@testing-library/dom": "^10.4.0",
+    "@testing-library/react": "^16.0.1",
+    "@testing-library/react-render-stream": "^1.0.3",
+    "@testing-library/user-event": "^14.5.2",
+    "@types/babel__core": "^7.20.5",
+    "@types/babel__helper-module-imports": "^7.18.3",
+    "@types/json-stringify-safe": "^5.0.0",
+    "@types/nanoid": "^2.1.0",
+    "@types/node": "^20.11.0",
+    "@types/query-string": "^6.3.0",
+    "@types/react": "^19.0.1",
+    "@types/react-dom": "^19.0.1",
+    "@types/yargs": "^16.0.1",
+    "@typescript-eslint/eslint-plugin": "^6",
+    "@typescript-eslint/parser": "^6",
+    "axios": "^0.19.2",
+    "esbuild": "^0.25.1",
+    "esbuild-extra": "^0.4.0",
+    "eslint": "^7.25.0",
+    "eslint-config-prettier": "^9.1.0",
+    "eslint-config-react-app": "^7.0.1",
+    "eslint-plugin-flowtype": "^5.7.2",
+    "eslint-plugin-import": "^2.22.1",
+    "eslint-plugin-jsx-a11y": "^6.4.1",
+    "eslint-plugin-prettier": "^5.1.3",
+    "eslint-plugin-react": "^7.23.2",
+    "eslint-plugin-react-hooks": "^4.2.0",
+    "fs-extra": "^9.1.0",
+    "invariant": "^2.2.4",
+    "jsdom": "^25.0.1",
+    "json-stringify-safe": "^5.0.1",
+    "msw": "^2.1.4",
+    "node-fetch": "^3.3.2",
+    "prettier": "^3.2.5",
+    "query-string": "^7.0.1",
+    "react": "^19.0.0",
+    "react-dom": "^19.0.0",
+    "rimraf": "^3.0.2",
+    "size-limit": "^11.0.1",
+    "tslib": "^1.10.0",
+    "tsup": "^8.4.0",
+    "tsx": "^4.19.0",
+    "typescript": "^5.8.2",
+    "valibot": "^1.0.0",
+    "vite-tsconfig-paths": "^4.3.1",
+    "vitest": "^4",
+    "yargs": "^15.3.1"
+  },
+  "scripts": {
+    "clean": "rimraf dist",
+    "run-build": "tsup --config=$INIT_CWD/tsup.config.mts",
+    "build": "yarn clean && yarn run-build && tsx scripts/fixUniqueSymbolExports.mts",
+    "build-only": "yarn clean && yarn run-build",
+    "format": "prettier --write \"(src|examples)/**/*.{ts,tsx}\" \"**/*.md\"",
+    "format:check": "prettier --list-different \"(src|examples)/**/*.{ts,tsx}\" \"docs/*/**.md\"",
+    "lint": "eslint src examples",
+    "test": "vitest --typecheck --run ",
+    "test:watch": "vitest --watch",
+    "type-tests": "yarn tsc -p tsconfig.test.json --noEmit",
+    "prepack": "yarn build",
+    "size": "size-limit"
+  },
+  "files": [
+    "dist/",
+    "src/",
+    "query",
+    "react"
+  ],
+  "dependencies": {
+    "@standard-schema/spec": "^1.0.0",
+    "@standard-schema/utils": "^0.3.0",
+    "immer": "^11.0.0",
+    "redux": "^5.0.1",
+    "redux-thunk": "^3.1.0",
+    "reselect": "^5.1.0"
+  },
+  "peerDependencies": {
+    "react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
+    "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
+  },
+  "peerDependenciesMeta": {
+    "react": {
+      "optional": true
+    },
+    "react-redux": {
+      "optional": true
+    }
+  },
+  "sideEffects": false,
+  "bugs": {
+    "url": "https://github.com/reduxjs/redux-toolkit/issues"
+  },
+  "homepage": "https://redux-toolkit.js.org"
+}
Index: node_modules/@reduxjs/toolkit/query/package.json
===================================================================
--- node_modules/@reduxjs/toolkit/query/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/query/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+{
+  "name": "@reduxjs/toolkit-query",
+  "version": "1.0.0",
+  "description": "",
+  "type": "module",
+  "module": "../dist/query/rtk-query.legacy-esm.js",
+  "main": "../dist/query/cjs/index.js",
+  "types": "./../dist/query/index.d.ts",
+  "react-native": "./../dist/query/rtk-query.legacy-esm.js",
+  "author": "Mark Erikson <mark@isquaredsoftware.com>",
+  "license": "MIT",
+  "sideEffects": false
+}
Index: node_modules/@reduxjs/toolkit/query/react/package.json
===================================================================
--- node_modules/@reduxjs/toolkit/query/react/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/query/react/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+{
+  "name": "@reduxjs/toolkit-query-react",
+  "version": "1.0.0",
+  "description": "",
+  "type": "module",
+  "module": "../../dist/query/react/rtk-query-react.legacy-esm.js",
+  "main": "../../dist/query/react/cjs/index.js",
+  "types": "./../../dist/query/react/index.d.ts",
+  "react-native": "./../../dist/query/react/rtk-query-react.legacy-esm.js",
+  "author": "Mark Erikson <mark@isquaredsoftware.com>",
+  "license": "MIT",
+  "sideEffects": false
+}
Index: node_modules/@reduxjs/toolkit/react/package.json
===================================================================
--- node_modules/@reduxjs/toolkit/react/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/react/package.json	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+{
+  "name": "@reduxjs/toolkit-react",
+  "version": "1.0.0",
+  "description": "",
+  "type": "module",
+  "module": "../dist/react/redux-toolkit-react.legacy-esm.js",
+  "main": "./../dist/react/redux-toolkit-react.modern.mjs",
+  "types": "./../dist/react/index.d.ts",
+  "react-native": "./../dist/react/redux-toolkit-react.modern.mjs",
+  "author": "Mark Erikson <mark@isquaredsoftware.com>",
+  "license": "MIT",
+  "sideEffects": false
+}
Index: node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,34 @@
+import type { Middleware } from 'redux'
+import { isActionCreator as isRTKAction } from './createAction'
+
+export interface ActionCreatorInvariantMiddlewareOptions {
+  /**
+   * The function to identify whether a value is an action creator.
+   * The default checks for a function with a static type property and match method.
+   */
+  isActionCreator?: (action: unknown) => action is Function & { type?: unknown }
+}
+
+export function getMessage(type?: unknown) {
+  const splitType = type ? `${type}`.split('/') : []
+  const actionName = splitType[splitType.length - 1] || 'actionCreator'
+  return `Detected an action creator with type "${
+    type || 'unknown'
+  }" being dispatched. 
+Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`
+}
+
+export function createActionCreatorInvariantMiddleware(
+  options: ActionCreatorInvariantMiddlewareOptions = {},
+): Middleware {
+  if (process.env.NODE_ENV === 'production') {
+    return () => (next) => (action) => next(action)
+  }
+  const { isActionCreator = isRTKAction } = options
+  return () => (next) => (action) => {
+    if (isActionCreator(action)) {
+      console.warn(getMessage(action.type))
+    }
+    return next(action)
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,128 @@
+import type { StoreEnhancer } from 'redux'
+
+export const SHOULD_AUTOBATCH = 'RTK_autoBatch'
+
+export const prepareAutoBatched =
+  <T>() =>
+  (payload: T): { payload: T; meta: unknown } => ({
+    payload,
+    meta: { [SHOULD_AUTOBATCH]: true },
+  })
+
+const createQueueWithTimer = (timeout: number) => {
+  return (notify: () => void) => {
+    setTimeout(notify, timeout)
+  }
+}
+
+export type AutoBatchOptions =
+  | { type: 'tick' }
+  | { type: 'timer'; timeout: number }
+  | { type: 'raf' }
+  | { type: 'callback'; queueNotification: (notify: () => void) => void }
+
+/**
+ * A Redux store enhancer that watches for "low-priority" actions, and delays
+ * notifying subscribers until either the queued callback executes or the
+ * next "standard-priority" action is dispatched.
+ *
+ * This allows dispatching multiple "low-priority" actions in a row with only
+ * a single subscriber notification to the UI after the sequence of actions
+ * is finished, thus improving UI re-render performance.
+ *
+ * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
+ * This can be added to `action.meta` manually, or by using the
+ * `prepareAutoBatched` helper.
+ *
+ * By default, it will queue a notification for the end of the event loop tick.
+ * However, you can pass several other options to configure the behavior:
+ * - `{type: 'tick'}`: queues using `queueMicrotask`
+ * - `{type: 'timer', timeout: number}`: queues using `setTimeout`
+ * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
+ * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
+ *
+ *
+ */
+export const autoBatchEnhancer =
+  (options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>
+  (next) =>
+  (...args) => {
+    const store = next(...args)
+
+    let notifying = true
+    let shouldNotifyAtEndOfTick = false
+    let notificationQueued = false
+
+    const listeners = new Set<() => void>()
+
+    const queueCallback =
+      options.type === 'tick'
+        ? queueMicrotask
+        : options.type === 'raf'
+          ? // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
+            typeof window !== 'undefined' && window.requestAnimationFrame
+            ? window.requestAnimationFrame
+            : createQueueWithTimer(10)
+          : options.type === 'callback'
+            ? options.queueNotification
+            : createQueueWithTimer(options.timeout)
+
+    const notifyListeners = () => {
+      // We're running at the end of the event loop tick.
+      // Run the real listener callbacks to actually update the UI.
+      notificationQueued = false
+      if (shouldNotifyAtEndOfTick) {
+        shouldNotifyAtEndOfTick = false
+        listeners.forEach((l) => l())
+      }
+    }
+
+    return Object.assign({}, store, {
+      // Override the base `store.subscribe` method to keep original listeners
+      // from running if we're delaying notifications
+      subscribe(listener: () => void) {
+        // Each wrapped listener will only call the real listener if
+        // the `notifying` flag is currently active when it's called.
+        // This lets the base store work as normal, while the actual UI
+        // update becomes controlled by this enhancer.
+        const wrappedListener: typeof listener = () => notifying && listener()
+        const unsubscribe = store.subscribe(wrappedListener)
+        listeners.add(listener)
+        return () => {
+          unsubscribe()
+          listeners.delete(listener)
+        }
+      },
+      // Override the base `store.dispatch` method so that we can check actions
+      // for the `shouldAutoBatch` flag and determine if batching is active
+      dispatch(action: any) {
+        try {
+          // If the action does _not_ have the `shouldAutoBatch` flag,
+          // we resume/continue normal notify-after-each-dispatch behavior
+          notifying = !action?.meta?.[SHOULD_AUTOBATCH]
+          // If a `notifyListeners` microtask was queued, you can't cancel it.
+          // Instead, we set a flag so that it's a no-op when it does run
+          shouldNotifyAtEndOfTick = !notifying
+          if (shouldNotifyAtEndOfTick) {
+            // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue
+            // a microtask to notify listeners at the end of the event loop tick.
+            // Make sure we only enqueue this _once_ per tick.
+            if (!notificationQueued) {
+              notificationQueued = true
+              queueCallback(notifyListeners)
+            }
+          }
+          // Go ahead and process the action as usual, including reducers.
+          // If normal notification behavior is enabled, the store will notify
+          // all of its own listeners, and the wrapper callbacks above will
+          // see `notifying` is true and pass on to the real listener callbacks.
+          // If we're "batching" behavior, then the wrapped callbacks will
+          // bail out, causing the base store notification behavior to be no-ops.
+          return store.dispatch(action)
+        } finally {
+          // Assume we're back to normal behavior after each action
+          notifying = true
+        }
+      },
+    })
+  }
Index: node_modules/@reduxjs/toolkit/src/combineSlices.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/combineSlices.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/combineSlices.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,487 @@
+import type {
+  PreloadedStateShapeFromReducersMapObject,
+  Reducer,
+  StateFromReducersMapObject,
+  UnknownAction,
+} from 'redux'
+import { combineReducers } from 'redux'
+import { nanoid } from './nanoid'
+import type {
+  Id,
+  NonUndefined,
+  Tail,
+  UnionToIntersection,
+  WithOptionalProp,
+} from './tsHelpers'
+import { getOrInsertComputed } from './utils'
+
+type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
+  reducerPath: ReducerPath
+  reducer: Reducer<State, any, PreloadedState>
+}
+
+type AnySliceLike = SliceLike<string, any>
+
+type SliceLikeReducerPath<A extends AnySliceLike> =
+  A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never
+
+type SliceLikeState<A extends AnySliceLike> =
+  A extends SliceLike<any, infer State, any> ? State : never
+
+type SliceLikePreloadedState<A extends AnySliceLike> =
+  A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never
+
+export type WithSlice<A extends AnySliceLike> = {
+  [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>
+}
+
+export type WithSlicePreloadedState<A extends AnySliceLike> = {
+  [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>
+}
+
+type ReducerMap = Record<string, Reducer>
+
+type ExistingSliceLike<DeclaredState, PreloadedState> = {
+  [ReducerPath in keyof DeclaredState]: SliceLike<
+    ReducerPath & string,
+    NonUndefined<DeclaredState[ReducerPath]>,
+    NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>
+  >
+}[keyof DeclaredState]
+
+export type InjectConfig = {
+  /**
+   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
+   */
+  overrideExisting?: boolean
+}
+
+/**
+ * A reducer that allows for slices/reducers to be injected after initialisation.
+ */
+export interface CombinedSliceReducer<
+  InitialState,
+  DeclaredState extends InitialState = InitialState,
+  PreloadedState extends Partial<
+    Record<keyof PreloadedState, any>
+  > = Partial<DeclaredState>,
+> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
+  /**
+   * Provide a type for slices that will be injected lazily.
+   *
+   * One way to do this would be with interface merging:
+   * ```ts
+   *
+   * export interface LazyLoadedSlices {}
+   *
+   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+   *
+   * // elsewhere
+   *
+   * declare module './reducer' {
+   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+   * }
+   *
+   * const withBoolean = rootReducer.inject(booleanSlice);
+   *
+   * // elsewhere again
+   *
+   * declare module './reducer' {
+   *   export interface LazyLoadedSlices {
+   *     customName: CustomState
+   *   }
+   * }
+   *
+   * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
+   * ```
+   */
+  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<
+    InitialState,
+    Id<DeclaredState & Partial<Lazy>>,
+    Id<PreloadedState & Partial<LazyPreloaded>>
+  >
+
+  /**
+   * Inject a slice.
+   *
+   * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+   *
+   * ```ts
+   * rootReducer.inject(booleanSlice)
+   * rootReducer.inject(baseApi)
+   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+   * ```
+   *
+   */
+  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(
+    slice: Sl,
+    config?: InjectConfig,
+  ): CombinedSliceReducer<
+    InitialState,
+    Id<DeclaredState & WithSlice<Sl>>,
+    Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>
+  >
+
+  /**
+   * Inject a slice.
+   *
+   * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
+   *
+   * ```ts
+   * rootReducer.inject(booleanSlice)
+   * rootReducer.inject(baseApi)
+   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
+   * ```
+   *
+   */
+  inject<ReducerPath extends string, State, PreloadedState = State>(
+    slice: SliceLike<
+      ReducerPath,
+      State & (ReducerPath extends keyof DeclaredState ? never : State),
+      PreloadedState &
+        (ReducerPath extends keyof PreloadedState ? never : PreloadedState)
+    >,
+    config?: InjectConfig,
+  ): CombinedSliceReducer<
+    InitialState,
+    Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>,
+    Id<
+      PreloadedState &
+        WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>
+    >
+  >
+
+  /**
+   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+   *
+   * ```ts
+   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+   * //                                                                ^? boolean | undefined
+   *
+   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+   *   return state.boolean;
+   *   //           ^? boolean
+   * })
+   * ```
+   *
+   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+   *
+   * ```ts
+   *
+   * export interface LazyLoadedSlices {};
+   *
+   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+   *
+   * export const rootReducer = combineSlices({ inner: innerReducer });
+   *
+   * export type RootState = ReturnType<typeof rootReducer>;
+   *
+   * // elsewhere
+   *
+   * declare module "./reducer.ts" {
+   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+   * }
+   *
+   * const withBool = innerReducer.inject(booleanSlice);
+   *
+   * const selectBoolean = withBool.selector(
+   *   (state) => state.boolean,
+   *   (rootState: RootState) => state.inner
+   * );
+   * //    now expects to be passed RootState instead of innerReducer state
+   *
+   * ```
+   *
+   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+   *
+   * ```ts
+   * const injectedReducer = rootReducer.inject(booleanSlice);
+   * const selectBoolean = injectedReducer.selector((state) => {
+   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+   *   return state.boolean
+   * })
+   * ```
+   */
+  selector: {
+    /**
+     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+     *
+     * ```ts
+     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+     * //                                                                ^? boolean | undefined
+     *
+     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+     *   return state.boolean;
+     *   //           ^? boolean
+     * })
+     * ```
+     *
+     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+     *
+     * ```ts
+     * const injectedReducer = rootReducer.inject(booleanSlice);
+     * const selectBoolean = injectedReducer.selector((state) => {
+     *   console.log(injectedReducer.selector.original(state).boolean) // undefined
+     *   return state.boolean
+     * })
+     * ```
+     */
+    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(
+      selectorFn: Selector,
+    ): (
+      state: WithOptionalProp<
+        Parameters<Selector>[0],
+        Exclude<keyof DeclaredState, keyof InitialState>
+      >,
+      ...args: Tail<Parameters<Selector>>
+    ) => ReturnType<Selector>
+
+    /**
+     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
+     *
+     * ```ts
+     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
+     * //                                                                ^? boolean | undefined
+     *
+     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
+     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined
+     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
+     *   return state.boolean;
+     *   //           ^? boolean
+     * })
+     * ```
+     *
+     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
+     *
+     * ```ts
+     *
+     * interface LazyLoadedSlices {};
+     *
+     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
+     *
+     * const rootReducer = combineSlices({ inner: innerReducer });
+     *
+     * type RootState = ReturnType<typeof rootReducer>;
+     *
+     * // elsewhere
+     *
+     * declare module "./reducer.ts" {
+     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
+     * }
+     *
+     * const withBool = innerReducer.inject(booleanSlice);
+     *
+     * const selectBoolean = withBool.selector(
+     *   (state) => state.boolean,
+     *   (rootState: RootState) => state.inner
+     * );
+     * //    now expects to be passed RootState instead of innerReducer state
+     *
+     * ```
+     *
+     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
+     *
+     * ```ts
+     * const injectedReducer = rootReducer.inject(booleanSlice);
+     * const selectBoolean = injectedReducer.selector((state) => {
+     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
+     *   return state.boolean
+     * })
+     * ```
+     */
+    <
+      Selector extends (state: DeclaredState, ...args: any[]) => unknown,
+      RootState,
+    >(
+      selectorFn: Selector,
+      selectState: (
+        rootState: RootState,
+        ...args: Tail<Parameters<Selector>>
+      ) => WithOptionalProp<
+        Parameters<Selector>[0],
+        Exclude<keyof DeclaredState, keyof InitialState>
+      >,
+    ): (
+      state: RootState,
+      ...args: Tail<Parameters<Selector>>
+    ) => ReturnType<Selector>
+    /**
+     * Returns the unproxied state. Useful for debugging.
+     * @param state state Proxy, that ensures injected reducers have value
+     * @returns original, unproxied state
+     * @throws if value passed is not a state Proxy
+     */
+    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>
+  }
+}
+
+type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> =
+  UnionToIntersection<
+    Slices[number] extends infer Slice
+      ? Slice extends AnySliceLike
+        ? WithSlice<Slice>
+        : StateFromReducersMapObject<Slice>
+      : never
+  >
+
+type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> =
+  UnionToIntersection<
+    Slices[number] extends infer Slice
+      ? Slice extends AnySliceLike
+        ? WithSlicePreloadedState<Slice>
+        : PreloadedStateShapeFromReducersMapObject<Slice>
+      : never
+  >
+
+const isSliceLike = (
+  maybeSliceLike: AnySliceLike | ReducerMap,
+): maybeSliceLike is AnySliceLike =>
+  'reducerPath' in maybeSliceLike &&
+  typeof maybeSliceLike.reducerPath === 'string'
+
+const getReducers = (slices: Array<AnySliceLike | ReducerMap>) =>
+  slices.flatMap<[string, Reducer]>((sliceOrMap) =>
+    isSliceLike(sliceOrMap)
+      ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]]
+      : Object.entries(sliceOrMap),
+  )
+
+const ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original')
+
+const isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE]
+
+const stateProxyMap = new WeakMap<object, object>()
+
+const createStateProxy = <State extends object>(
+  state: State,
+  reducerMap: Partial<Record<PropertyKey, Reducer>>,
+  initialStateCache: Record<PropertyKey, unknown>,
+) =>
+  getOrInsertComputed(
+    stateProxyMap,
+    state,
+    () =>
+      new Proxy(state, {
+        get: (target, prop, receiver) => {
+          if (prop === ORIGINAL_STATE) return target
+          const result = Reflect.get(target, prop, receiver)
+          if (typeof result === 'undefined') {
+            const cached = initialStateCache[prop]
+            if (typeof cached !== 'undefined') return cached
+            const reducer = reducerMap[prop]
+            if (reducer) {
+              // ensure action type is random, to prevent reducer treating it differently
+              const reducerResult = reducer(undefined, { type: nanoid() })
+              if (typeof reducerResult === 'undefined') {
+                throw new Error(
+                  `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). ` +
+                    `If the state passed to the reducer is undefined, you must ` +
+                    `explicitly return the initial state. The initial state may ` +
+                    `not be undefined. If you don't want to set a value for this reducer, ` +
+                    `you can use null instead of undefined.`,
+                )
+              }
+              initialStateCache[prop] = reducerResult
+              return reducerResult
+            }
+          }
+          return result
+        },
+      }),
+  ) as State
+
+const original = (state: any) => {
+  if (!isStateProxy(state)) {
+    throw new Error('original must be used on state Proxy')
+  }
+  return state[ORIGINAL_STATE]
+}
+
+const emptyObject = {}
+const noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state
+
+export function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(
+  ...slices: Slices
+): CombinedSliceReducer<
+  Id<InitialState<Slices>>,
+  Id<InitialState<Slices>>,
+  Partial<Id<InitialPreloadedState<Slices>>>
+> {
+  const reducerMap = Object.fromEntries(getReducers(slices))
+
+  const getReducer = () =>
+    Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer
+
+  let reducer = getReducer()
+
+  function combinedReducer(
+    state: Record<string, unknown>,
+    action: UnknownAction,
+  ) {
+    return reducer(state, action)
+  }
+
+  combinedReducer.withLazyLoadedSlices = () => combinedReducer
+
+  const initialStateCache: Record<PropertyKey, unknown> = {}
+
+  const inject = (
+    slice: AnySliceLike,
+    config: InjectConfig = {},
+  ): typeof combinedReducer => {
+    const { reducerPath, reducer: reducerToInject } = slice
+
+    const currentReducer = reducerMap[reducerPath]
+    if (
+      !config.overrideExisting &&
+      currentReducer &&
+      currentReducer !== reducerToInject
+    ) {
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV === 'development'
+      ) {
+        console.error(
+          `called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``,
+        )
+      }
+
+      return combinedReducer
+    }
+
+    if (config.overrideExisting && currentReducer !== reducerToInject) {
+      delete initialStateCache[reducerPath]
+    }
+
+    reducerMap[reducerPath] = reducerToInject
+
+    reducer = getReducer()
+
+    return combinedReducer
+  }
+
+  const selector = Object.assign(
+    function makeSelector<State extends object, RootState, Args extends any[]>(
+      selectorFn: (state: State, ...args: Args) => any,
+      selectState?: (rootState: RootState, ...args: Args) => State,
+    ) {
+      return function selector(state: State, ...args: Args) {
+        return selectorFn(
+          createStateProxy(
+            selectState ? selectState(state as any, ...args) : state,
+            reducerMap,
+            initialStateCache,
+          ),
+          ...args,
+        )
+      }
+    },
+    { original },
+  )
+
+  return Object.assign(combinedReducer, { inject, selector }) as any
+}
Index: node_modules/@reduxjs/toolkit/src/configureStore.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/configureStore.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/configureStore.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,248 @@
+import type {
+  Reducer,
+  ReducersMapObject,
+  Middleware,
+  Action,
+  StoreEnhancer,
+  Store,
+  UnknownAction,
+} from 'redux'
+import {
+  applyMiddleware,
+  createStore,
+  compose,
+  combineReducers,
+  isPlainObject,
+} from './reduxImports'
+import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'
+import { composeWithDevTools } from './devtoolsExtension'
+
+import type {
+  ThunkMiddlewareFor,
+  GetDefaultMiddleware,
+} from './getDefaultMiddleware'
+import { buildGetDefaultMiddleware } from './getDefaultMiddleware'
+import type {
+  ExtractDispatchExtensions,
+  ExtractStoreExtensions,
+  ExtractStateExtensions,
+  UnknownIfNonSpecific,
+} from './tsHelpers'
+import type { Tuple } from './utils'
+import type { GetDefaultEnhancers } from './getDefaultEnhancers'
+import { buildGetDefaultEnhancers } from './getDefaultEnhancers'
+
+/**
+ * Options for `configureStore()`.
+ *
+ * @public
+ */
+export interface ConfigureStoreOptions<
+  S = any,
+  A extends Action = UnknownAction,
+  M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,
+  E extends Tuple<Enhancers> = Tuple<Enhancers>,
+  P = S,
+> {
+  /**
+   * A single reducer function that will be used as the root reducer, or an
+   * object of slice reducers that will be passed to `combineReducers()`.
+   */
+  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>
+
+  /**
+   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
+   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
+   *
+   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
+   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
+   */
+  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M
+
+  /**
+   * Whether to enable Redux DevTools integration. Defaults to `true`.
+   *
+   * Additional configuration can be done by passing Redux DevTools options
+   */
+  devTools?: boolean | DevToolsOptions
+
+  /**
+   * Whether to check for duplicate middleware instances. Defaults to `true`.
+   */
+  duplicateMiddlewareCheck?: boolean
+
+  /**
+   * The initial state, same as Redux's createStore.
+   * You may optionally specify it to hydrate the state
+   * from the server in universal apps, or to restore a previously serialized
+   * user session. If you use `combineReducers()` to produce the root reducer
+   * function (either directly or indirectly by passing an object as `reducer`),
+   * this must be an object with the same shape as the reducer map keys.
+   */
+  // we infer here, and instead complain if the reducer doesn't match
+  preloadedState?: P
+
+  /**
+   * The store enhancers to apply. See Redux's `createStore()`.
+   * All enhancers will be included before the DevTools Extension enhancer.
+   * If you need to customize the order of enhancers, supply a callback
+   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
+   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
+   * If you only need to add middleware, you can use the `middleware` parameter instead.
+   */
+  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E
+}
+
+export type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>
+
+type Enhancers = ReadonlyArray<StoreEnhancer>
+
+/**
+ * A Redux store returned by `configureStore()`. Supports dispatching
+ * side-effectful _thunks_ in addition to plain actions.
+ *
+ * @public
+ */
+export type EnhancedStore<
+  S = any,
+  A extends Action = UnknownAction,
+  E extends Enhancers = Enhancers,
+> = ExtractStoreExtensions<E> &
+  Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>
+
+/**
+ * A friendly abstraction over the standard Redux `createStore()` function.
+ *
+ * @param options The store configuration.
+ * @returns A configured Redux store.
+ *
+ * @public
+ */
+export function configureStore<
+  S = any,
+  A extends Action = UnknownAction,
+  M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,
+  E extends Tuple<Enhancers> = Tuple<
+    [StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]
+  >,
+  P = S,
+>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {
+  const getDefaultMiddleware = buildGetDefaultMiddleware<S>()
+
+  const {
+    reducer = undefined,
+    middleware,
+    devTools = true,
+    duplicateMiddlewareCheck = true,
+    preloadedState = undefined,
+    enhancers = undefined,
+  } = options || {}
+
+  let rootReducer: Reducer<S, A, P>
+
+  if (typeof reducer === 'function') {
+    rootReducer = reducer
+  } else if (isPlainObject(reducer)) {
+    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>
+  } else {
+    throw new Error(
+      '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
+    )
+  }
+
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    middleware &&
+    typeof middleware !== 'function'
+  ) {
+    throw new Error('`middleware` field must be a callback')
+  }
+
+  let finalMiddleware: Tuple<Middlewares<S>>
+  if (typeof middleware === 'function') {
+    finalMiddleware = middleware(getDefaultMiddleware)
+
+    if (
+      process.env.NODE_ENV !== 'production' &&
+      !Array.isArray(finalMiddleware)
+    ) {
+      throw new Error(
+        'when using a middleware builder function, an array of middleware must be returned',
+      )
+    }
+  } else {
+    finalMiddleware = getDefaultMiddleware()
+  }
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    finalMiddleware.some((item: any) => typeof item !== 'function')
+  ) {
+    throw new Error(
+      'each middleware provided to configureStore must be a function',
+    )
+  }
+
+  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {
+    let middlewareReferences = new Set<Middleware<any, S>>()
+    finalMiddleware.forEach((middleware) => {
+      if (middlewareReferences.has(middleware)) {
+        throw new Error(
+          'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
+        )
+      }
+      middlewareReferences.add(middleware)
+    })
+  }
+
+  let finalCompose = compose
+
+  if (devTools) {
+    finalCompose = composeWithDevTools({
+      // Enable capture of stack traces for dispatched Redux actions
+      trace: process.env.NODE_ENV !== 'production',
+      ...(typeof devTools === 'object' && devTools),
+    })
+  }
+
+  const middlewareEnhancer = applyMiddleware(...finalMiddleware)
+
+  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)
+
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    enhancers &&
+    typeof enhancers !== 'function'
+  ) {
+    throw new Error('`enhancers` field must be a callback')
+  }
+
+  let storeEnhancers =
+    typeof enhancers === 'function'
+      ? enhancers(getDefaultEnhancers)
+      : getDefaultEnhancers()
+
+  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {
+    throw new Error('`enhancers` callback must return an array')
+  }
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    storeEnhancers.some((item: any) => typeof item !== 'function')
+  ) {
+    throw new Error(
+      'each enhancer provided to configureStore must be a function',
+    )
+  }
+  if (
+    process.env.NODE_ENV !== 'production' &&
+    finalMiddleware.length &&
+    !storeEnhancers.includes(middlewareEnhancer)
+  ) {
+    console.error(
+      'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
+    )
+  }
+
+  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers)
+
+  return createStore(rootReducer, preloadedState as P, composedEnhancer)
+}
Index: node_modules/@reduxjs/toolkit/src/createAction.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createAction.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createAction.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,324 @@
+import { isAction } from './reduxImports'
+import type {
+  IsUnknownOrNonInferrable,
+  IfMaybeUndefined,
+  IfVoid,
+  IsAny,
+} from './tsHelpers'
+import { hasMatchFunction } from './tsHelpers'
+
+/**
+ * An action with a string type and an associated payload. This is the
+ * type of action returned by `createAction()` action creators.
+ *
+ * @template P The type of the action's payload.
+ * @template T the type used for the action type.
+ * @template M The type of the action's meta (optional)
+ * @template E The type of the action's error (optional)
+ *
+ * @public
+ */
+export type PayloadAction<
+  P = void,
+  T extends string = string,
+  M = never,
+  E = never,
+> = {
+  payload: P
+  type: T
+} & ([M] extends [never]
+  ? {}
+  : {
+      meta: M
+    }) &
+  ([E] extends [never]
+    ? {}
+    : {
+        error: E
+      })
+
+/**
+ * A "prepare" method to be used as the second parameter of `createAction`.
+ * Takes any number of arguments and returns a Flux Standard Action without
+ * type (will be added later) that *must* contain a payload (might be undefined).
+ *
+ * @public
+ */
+export type PrepareAction<P> =
+  | ((...args: any[]) => { payload: P })
+  | ((...args: any[]) => { payload: P; meta: any })
+  | ((...args: any[]) => { payload: P; error: any })
+  | ((...args: any[]) => { payload: P; meta: any; error: any })
+
+/**
+ * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
+ *
+ * @internal
+ */
+export type _ActionCreatorWithPreparedPayload<
+  PA extends PrepareAction<any> | void,
+  T extends string = string,
+> =
+  PA extends PrepareAction<infer P>
+    ? ActionCreatorWithPreparedPayload<
+        Parameters<PA>,
+        P,
+        T,
+        ReturnType<PA> extends {
+          error: infer E
+        }
+          ? E
+          : never,
+        ReturnType<PA> extends {
+          meta: infer M
+        }
+          ? M
+          : never
+      >
+    : void
+
+/**
+ * Basic type for all action creators.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ */
+export type BaseActionCreator<P, T extends string, M = never, E = never> = {
+  type: T
+  match: (action: unknown) => action is PayloadAction<P, T, M, E>
+}
+
+/**
+ * An action creator that takes multiple arguments that are passed
+ * to a `PrepareAction` method to create the final Action.
+ * @typeParam Args arguments for the action creator function
+ * @typeParam P `payload` type
+ * @typeParam T `type` name
+ * @typeParam E optional `error` type
+ * @typeParam M optional `meta` type
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithPreparedPayload<
+  Args extends unknown[],
+  P,
+  T extends string = string,
+  E = never,
+  M = never,
+> extends BaseActionCreator<P, T, M, E> {
+  /**
+   * Calling this {@link redux#ActionCreator} with `Args` will return
+   * an Action with a payload of type `P` and (depending on the `PrepareAction`
+   * method used) a `meta`- and `error` property of types `M` and `E` respectively.
+   */
+  (...args: Args): PayloadAction<P, T, M, E>
+}
+
+/**
+ * An action creator of type `T` that takes an optional payload of type `P`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithOptionalPayload<P, T extends string = string>
+  extends BaseActionCreator<P, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} with an argument will
+   * return a {@link PayloadAction} of type `T` with a payload of `P`.
+   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
+   */
+  (payload?: P): PayloadAction<P, T>
+}
+
+/**
+ * An action creator of type `T` that takes no payload.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithoutPayload<T extends string = string>
+  extends BaseActionCreator<undefined, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} will
+   * return a {@link PayloadAction} of type `T` with a payload of `undefined`
+   */
+  (noArgument: void): PayloadAction<undefined, T>
+}
+
+/**
+ * An action creator of type `T` that requires a payload of type P.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithPayload<P, T extends string = string>
+  extends BaseActionCreator<P, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} with an argument will
+   * return a {@link PayloadAction} of type `T` with a payload of `P`
+   */
+  (payload: P): PayloadAction<P, T>
+}
+
+/**
+ * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
+ *
+ * @inheritdoc {redux#ActionCreator}
+ *
+ * @public
+ */
+export interface ActionCreatorWithNonInferrablePayload<
+  T extends string = string,
+> extends BaseActionCreator<unknown, T> {
+  /**
+   * Calling this {@link redux#ActionCreator} with an argument will
+   * return a {@link PayloadAction} of type `T` with a payload
+   * of exactly the type of the argument.
+   */
+  <PT extends unknown>(payload: PT): PayloadAction<PT, T>
+}
+
+/**
+ * An action creator that produces actions with a `payload` attribute.
+ *
+ * @typeParam P the `payload` type
+ * @typeParam T the `type` of the resulting action
+ * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
+ *
+ * @public
+ */
+export type PayloadActionCreator<
+  P = void,
+  T extends string = string,
+  PA extends PrepareAction<P> | void = void,
+> = IfPrepareActionMethodProvided<
+  PA,
+  _ActionCreatorWithPreparedPayload<PA, T>,
+  // else
+  IsAny<
+    P,
+    ActionCreatorWithPayload<any, T>,
+    IsUnknownOrNonInferrable<
+      P,
+      ActionCreatorWithNonInferrablePayload<T>,
+      // else
+      IfVoid<
+        P,
+        ActionCreatorWithoutPayload<T>,
+        // else
+        IfMaybeUndefined<
+          P,
+          ActionCreatorWithOptionalPayload<P, T>,
+          // else
+          ActionCreatorWithPayload<P, T>
+        >
+      >
+    >
+  >
+>
+
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+export function createAction<P = void, T extends string = string>(
+  type: T,
+): PayloadActionCreator<P, T>
+
+/**
+ * A utility function to create an action creator for the given action type
+ * string. The action creator accepts a single argument, which will be included
+ * in the action object as a field called payload. The action creator function
+ * will also have its toString() overridden so that it returns the action type.
+ *
+ * @param type The action type to use for created actions.
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
+ *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
+ *
+ * @public
+ */
+export function createAction<
+  PA extends PrepareAction<any>,
+  T extends string = string,
+>(
+  type: T,
+  prepareAction: PA,
+): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
+
+export function createAction(type: string, prepareAction?: Function): any {
+  function actionCreator(...args: any[]) {
+    if (prepareAction) {
+      let prepared = prepareAction(...args)
+      if (!prepared) {
+        throw new Error('prepareAction did not return an object')
+      }
+
+      return {
+        type,
+        payload: prepared.payload,
+        ...('meta' in prepared && { meta: prepared.meta }),
+        ...('error' in prepared && { error: prepared.error }),
+      }
+    }
+    return { type, payload: args[0] }
+  }
+
+  actionCreator.toString = () => `${type}`
+
+  actionCreator.type = type
+
+  actionCreator.match = (action: unknown): action is PayloadAction =>
+    isAction(action) && action.type === type
+
+  return actionCreator
+}
+
+/**
+ * Returns true if value is an RTK-like action creator, with a static type property and match method.
+ */
+export function isActionCreator(
+  action: unknown,
+): action is BaseActionCreator<unknown, string> & Function {
+  return (
+    typeof action === 'function' &&
+    'type' in action &&
+    // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
+    hasMatchFunction(action as any)
+  )
+}
+
+/**
+ * Returns true if value is an action with a string type and valid Flux Standard Action keys.
+ */
+export function isFSA(action: unknown): action is {
+  type: string
+  payload?: unknown
+  error?: unknown
+  meta?: unknown
+} {
+  return isAction(action) && Object.keys(action).every(isValidKey)
+}
+
+function isValidKey(key: string) {
+  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1
+}
+
+// helper types for more readable typings
+
+type IfPrepareActionMethodProvided<
+  PA extends PrepareAction<any> | void,
+  True,
+  False,
+> = PA extends (...args: any[]) => any ? True : False
Index: node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,791 @@
+import type { Dispatch, UnknownAction } from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import type { ActionCreatorWithPreparedPayload } from './createAction'
+import { createAction } from './createAction'
+import { isAnyOf } from './matchers'
+import { nanoid } from './nanoid'
+import type {
+  FallbackIfUnknown,
+  Id,
+  IsAny,
+  IsUnknown,
+  SafePromise,
+} from './tsHelpers'
+
+export type BaseThunkAPI<
+  S,
+  E,
+  D extends Dispatch = Dispatch,
+  RejectedValue = unknown,
+  RejectedMeta = unknown,
+  FulfilledMeta = unknown,
+> = {
+  dispatch: D
+  getState: () => S
+  extra: E
+  requestId: string
+  signal: AbortSignal
+  abort: (reason?: string) => void
+  rejectWithValue: IsUnknown<
+    RejectedMeta,
+    (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,
+    (
+      value: RejectedValue,
+      meta: RejectedMeta,
+    ) => RejectWithValue<RejectedValue, RejectedMeta>
+  >
+  fulfillWithValue: IsUnknown<
+    FulfilledMeta,
+    <FulfilledValue>(value: FulfilledValue) => FulfilledValue,
+    <FulfilledValue>(
+      value: FulfilledValue,
+      meta: FulfilledMeta,
+    ) => FulfillWithMeta<FulfilledValue, FulfilledMeta>
+  >
+}
+
+/**
+ * @public
+ */
+export interface SerializedError {
+  name?: string
+  message?: string
+  stack?: string
+  code?: string
+}
+
+const commonProperties: Array<keyof SerializedError> = [
+  'name',
+  'message',
+  'stack',
+  'code',
+]
+
+class RejectWithValue<Payload, RejectedMeta> {
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  private readonly _type!: 'RejectWithValue'
+  constructor(
+    public readonly payload: Payload,
+    public readonly meta: RejectedMeta,
+  ) {}
+}
+
+class FulfillWithMeta<Payload, FulfilledMeta> {
+  /*
+  type-only property to distinguish between RejectWithValue and FulfillWithMeta
+  does not exist at runtime
+  */
+  private readonly _type!: 'FulfillWithMeta'
+  constructor(
+    public readonly payload: Payload,
+    public readonly meta: FulfilledMeta,
+  ) {}
+}
+
+/**
+ * Serializes an error into a plain object.
+ * Reworked from https://github.com/sindresorhus/serialize-error
+ *
+ * @public
+ */
+export const miniSerializeError = (value: any): SerializedError => {
+  if (typeof value === 'object' && value !== null) {
+    const simpleError: SerializedError = {}
+    for (const property of commonProperties) {
+      if (typeof value[property] === 'string') {
+        simpleError[property] = value[property]
+      }
+    }
+
+    return simpleError
+  }
+
+  return { message: String(value) }
+}
+
+export type AsyncThunkConfig = {
+  state?: unknown
+  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>
+  extra?: unknown
+  rejectValue?: unknown
+  serializedErrorType?: unknown
+  pendingMeta?: unknown
+  fulfilledMeta?: unknown
+  rejectedMeta?: unknown
+}
+
+export type GetState<ThunkApiConfig> = ThunkApiConfig extends {
+  state: infer State
+}
+  ? State
+  : unknown
+
+type GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }
+  ? Extra
+  : unknown
+type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
+  dispatch: infer Dispatch
+}
+  ? FallbackIfUnknown<
+      Dispatch,
+      ThunkDispatch<
+        GetState<ThunkApiConfig>,
+        GetExtra<ThunkApiConfig>,
+        UnknownAction
+      >
+    >
+  : ThunkDispatch<
+      GetState<ThunkApiConfig>,
+      GetExtra<ThunkApiConfig>,
+      UnknownAction
+    >
+
+export type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
+  GetState<ThunkApiConfig>,
+  GetExtra<ThunkApiConfig>,
+  GetDispatch<ThunkApiConfig>,
+  GetRejectValue<ThunkApiConfig>,
+  GetRejectedMeta<ThunkApiConfig>,
+  GetFulfilledMeta<ThunkApiConfig>
+>
+
+type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
+  rejectValue: infer RejectValue
+}
+  ? RejectValue
+  : unknown
+
+type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
+  pendingMeta: infer PendingMeta
+}
+  ? PendingMeta
+  : unknown
+
+type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
+  fulfilledMeta: infer FulfilledMeta
+}
+  ? FulfilledMeta
+  : unknown
+
+type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
+  rejectedMeta: infer RejectedMeta
+}
+  ? RejectedMeta
+  : unknown
+
+type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
+  serializedErrorType: infer GetSerializedErrorType
+}
+  ? GetSerializedErrorType
+  : SerializedError
+
+type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)
+
+/**
+ * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+export type AsyncThunkPayloadCreatorReturnValue<
+  Returned,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = MaybePromise<
+  | IsUnknown<
+      GetFulfilledMeta<ThunkApiConfig>,
+      Returned,
+      FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>
+    >
+  | RejectWithValue<
+      GetRejectValue<ThunkApiConfig>,
+      GetRejectedMeta<ThunkApiConfig>
+    >
+>
+/**
+ * A type describing the `payloadCreator` argument to `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+export type AsyncThunkPayloadCreator<
+  Returned,
+  ThunkArg = void,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = (
+  arg: ThunkArg,
+  thunkAPI: GetThunkAPI<ThunkApiConfig>,
+) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>
+
+/**
+ * A ThunkAction created by `createAsyncThunk`.
+ * Dispatching it returns a Promise for either a
+ * fulfilled or rejected action.
+ * Also, the returned value contains an `abort()` method
+ * that allows the asyncAction to be cancelled from the outside.
+ *
+ * @public
+ */
+export type AsyncThunkAction<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = (
+  dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,
+  getState: () => GetState<ThunkApiConfig>,
+  extra: GetExtra<ThunkApiConfig>,
+) => SafePromise<
+  | ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>
+  | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>
+> & {
+  abort: (reason?: string) => void
+  requestId: string
+  arg: ThunkArg
+  unwrap: () => Promise<Returned>
+}
+
+/**
+ * Config provided when calling the async thunk action creator.
+ */
+export interface AsyncThunkDispatchConfig {
+  /**
+   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
+   */
+  signal?: AbortSignal
+}
+
+type AsyncThunkActionCreator<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = IsAny<
+  ThunkArg,
+  // any handling
+  (
+    arg: ThunkArg,
+    config?: AsyncThunkDispatchConfig,
+  ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
+  // unknown handling
+  unknown extends ThunkArg
+    ? (
+        arg: ThunkArg,
+        config?: AsyncThunkDispatchConfig,
+      ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined
+    : [ThunkArg] extends [void] | [undefined]
+      ? (
+          arg?: undefined,
+          config?: AsyncThunkDispatchConfig,
+        ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void
+      : [void] extends [ThunkArg] // make optional
+        ? (
+            arg?: ThunkArg,
+            config?: AsyncThunkDispatchConfig,
+          ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined
+        : [undefined] extends [ThunkArg]
+          ? WithStrictNullChecks<
+              // with strict nullChecks: make optional
+              (
+                arg?: ThunkArg,
+                config?: AsyncThunkDispatchConfig,
+              ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
+              // without strict null checks this will match everything, so don't make it optional
+              (
+                arg: ThunkArg,
+                config?: AsyncThunkDispatchConfig,
+              ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
+            > // default case: normal argument
+          : (
+              arg: ThunkArg,
+              config?: AsyncThunkDispatchConfig,
+            ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
+>
+
+/**
+ * Options object for `createAsyncThunk`.
+ *
+ * @public
+ */
+export type AsyncThunkOptions<
+  ThunkArg = void,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = {
+  /**
+   * A method to control whether the asyncThunk should be executed. Has access to the
+   * `arg`, `api.getState()` and `api.extra` arguments.
+   *
+   * @returns `false` if it should be skipped
+   */
+  condition?(
+    arg: ThunkArg,
+    api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
+  ): MaybePromise<boolean | undefined>
+  /**
+   * If `condition` returns `false`, the asyncThunk will be skipped.
+   * This option allows you to control whether a `rejected` action with `meta.condition == false`
+   * will be dispatched or not.
+   *
+   * @default `false`
+   */
+  dispatchConditionRejection?: boolean
+
+  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>
+
+  /**
+   * A function to use when generating the `requestId` for the request sequence.
+   *
+   * @default `nanoid`
+   */
+  idGenerator?: (arg: ThunkArg) => string
+} & IsUnknown<
+  GetPendingMeta<ThunkApiConfig>,
+  {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     *
+     * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
+     * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
+     */
+    getPendingMeta?(
+      base: {
+        arg: ThunkArg
+        requestId: string
+      },
+      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
+    ): GetPendingMeta<ThunkApiConfig>
+  },
+  {
+    /**
+     * A method to generate additional properties to be added to `meta` of the pending action.
+     */
+    getPendingMeta(
+      base: {
+        arg: ThunkArg
+        requestId: string
+      },
+      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
+    ): GetPendingMeta<ThunkApiConfig>
+  }
+>
+
+export type AsyncThunkPendingActionCreator<
+  ThunkArg,
+  ThunkApiConfig = {},
+> = ActionCreatorWithPreparedPayload<
+  [string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],
+  undefined,
+  string,
+  never,
+  {
+    arg: ThunkArg
+    requestId: string
+    requestStatus: 'pending'
+  } & GetPendingMeta<ThunkApiConfig>
+>
+
+export type AsyncThunkRejectedActionCreator<
+  ThunkArg,
+  ThunkApiConfig = {},
+> = ActionCreatorWithPreparedPayload<
+  [
+    Error | null,
+    string,
+    ThunkArg,
+    GetRejectValue<ThunkApiConfig>?,
+    GetRejectedMeta<ThunkApiConfig>?,
+  ],
+  GetRejectValue<ThunkApiConfig> | undefined,
+  string,
+  GetSerializedErrorType<ThunkApiConfig>,
+  {
+    arg: ThunkArg
+    requestId: string
+    requestStatus: 'rejected'
+    aborted: boolean
+    condition: boolean
+  } & (
+    | ({ rejectedWithValue: false } & {
+        [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined
+      })
+    | ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)
+  )
+>
+
+export type AsyncThunkFulfilledActionCreator<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig = {},
+> = ActionCreatorWithPreparedPayload<
+  [Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],
+  Returned,
+  string,
+  never,
+  {
+    arg: ThunkArg
+    requestId: string
+    requestStatus: 'fulfilled'
+  } & GetFulfilledMeta<ThunkApiConfig>
+>
+
+/**
+ * A type describing the return value of `createAsyncThunk`.
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
+ *
+ * @public
+ */
+export type AsyncThunk<
+  Returned,
+  ThunkArg,
+  ThunkApiConfig extends AsyncThunkConfig,
+> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
+  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>
+  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
+  fulfilled: AsyncThunkFulfilledActionCreator<
+    Returned,
+    ThunkArg,
+    ThunkApiConfig
+  >
+  // matchSettled?
+  settled: (
+    action: any,
+  ) => action is ReturnType<
+    | AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
+    | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>
+  >
+  typePrefix: string
+}
+
+export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
+  NewConfig & Omit<OldConfig, keyof NewConfig>
+>
+
+export type CreateAsyncThunkFunction<
+  CurriedThunkApiConfig extends AsyncThunkConfig,
+> = {
+  /**
+   *
+   * @param typePrefix
+   * @param payloadCreator
+   * @param options
+   *
+   * @public
+   */
+  // separate signature without `AsyncThunkConfig` for better inference
+  <Returned, ThunkArg = void>(
+    typePrefix: string,
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      CurriedThunkApiConfig
+    >,
+    options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,
+  ): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>
+
+  /**
+   *
+   * @param typePrefix
+   * @param payloadCreator
+   * @param options
+   *
+   * @public
+   */
+  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(
+    typePrefix: string,
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+    >,
+    options?: AsyncThunkOptions<
+      ThunkArg,
+      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+    >,
+  ): AsyncThunk<
+    Returned,
+    ThunkArg,
+    OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+  >
+}
+
+type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> =
+  CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
+    withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
+      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+    >
+  }
+
+const externalAbortMessage = 'External signal was aborted'
+
+export const createAsyncThunk = /* @__PURE__ */ (() => {
+  function createAsyncThunk<
+    Returned,
+    ThunkArg,
+    ThunkApiConfig extends AsyncThunkConfig,
+  >(
+    typePrefix: string,
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig
+    >,
+    options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,
+  ): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
+    type RejectedValue = GetRejectValue<ThunkApiConfig>
+    type PendingMeta = GetPendingMeta<ThunkApiConfig>
+    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>
+    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>
+
+    const fulfilled: AsyncThunkFulfilledActionCreator<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig
+    > = createAction(
+      typePrefix + '/fulfilled',
+      (
+        payload: Returned,
+        requestId: string,
+        arg: ThunkArg,
+        meta?: FulfilledMeta,
+      ) => ({
+        payload,
+        meta: {
+          ...((meta as any) || {}),
+          arg,
+          requestId,
+          requestStatus: 'fulfilled' as const,
+        },
+      }),
+    )
+
+    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =
+      createAction(
+        typePrefix + '/pending',
+        (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({
+          payload: undefined,
+          meta: {
+            ...((meta as any) || {}),
+            arg,
+            requestId,
+            requestStatus: 'pending' as const,
+          },
+        }),
+      )
+
+    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =
+      createAction(
+        typePrefix + '/rejected',
+        (
+          error: Error | null,
+          requestId: string,
+          arg: ThunkArg,
+          payload?: RejectedValue,
+          meta?: RejectedMeta,
+        ) => ({
+          payload,
+          error: ((options && options.serializeError) || miniSerializeError)(
+            error || 'Rejected',
+          ) as GetSerializedErrorType<ThunkApiConfig>,
+          meta: {
+            ...((meta as any) || {}),
+            arg,
+            requestId,
+            rejectedWithValue: !!payload,
+            requestStatus: 'rejected' as const,
+            aborted: error?.name === 'AbortError',
+            condition: error?.name === 'ConditionError',
+          },
+        }),
+      )
+
+    function actionCreator(
+      arg: ThunkArg,
+      { signal }: AsyncThunkDispatchConfig = {},
+    ): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {
+      return (dispatch, getState, extra) => {
+        const requestId = options?.idGenerator
+          ? options.idGenerator(arg)
+          : nanoid()
+
+        const abortController = new AbortController()
+        let abortHandler: (() => void) | undefined
+        let abortReason: string | undefined
+
+        function abort(reason?: string) {
+          abortReason = reason
+          abortController.abort()
+        }
+
+        if (signal) {
+          if (signal.aborted) {
+            abort(externalAbortMessage)
+          } else {
+            signal.addEventListener(
+              'abort',
+              () => abort(externalAbortMessage),
+              { once: true },
+            )
+          }
+        }
+
+        const promise = (async function () {
+          let finalAction: ReturnType<typeof fulfilled | typeof rejected>
+          try {
+            let conditionResult = options?.condition?.(arg, { getState, extra })
+            if (isThenable(conditionResult)) {
+              conditionResult = await conditionResult
+            }
+
+            if (conditionResult === false || abortController.signal.aborted) {
+              // eslint-disable-next-line no-throw-literal
+              throw {
+                name: 'ConditionError',
+                message: 'Aborted due to condition callback returning false.',
+              }
+            }
+
+            const abortedPromise = new Promise<never>((_, reject) => {
+              abortHandler = () => {
+                reject({
+                  name: 'AbortError',
+                  message: abortReason || 'Aborted',
+                })
+              }
+              abortController.signal.addEventListener('abort', abortHandler, {
+                once: true,
+              })
+            })
+            dispatch(
+              pending(
+                requestId,
+                arg,
+                options?.getPendingMeta?.(
+                  { requestId, arg },
+                  { getState, extra },
+                ),
+              ) as any,
+            )
+            finalAction = await Promise.race([
+              abortedPromise,
+              Promise.resolve(
+                payloadCreator(arg, {
+                  dispatch,
+                  getState,
+                  extra,
+                  requestId,
+                  signal: abortController.signal,
+                  abort,
+                  rejectWithValue: ((
+                    value: RejectedValue,
+                    meta?: RejectedMeta,
+                  ) => {
+                    return new RejectWithValue(value, meta)
+                  }) as any,
+                  fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {
+                    return new FulfillWithMeta(value, meta)
+                  }) as any,
+                }),
+              ).then((result) => {
+                if (result instanceof RejectWithValue) {
+                  throw result
+                }
+                if (result instanceof FulfillWithMeta) {
+                  return fulfilled(result.payload, requestId, arg, result.meta)
+                }
+                return fulfilled(result as any, requestId, arg)
+              }),
+            ])
+          } catch (err) {
+            finalAction =
+              err instanceof RejectWithValue
+                ? rejected(null, requestId, arg, err.payload, err.meta)
+                : rejected(err as any, requestId, arg)
+          } finally {
+            if (abortHandler) {
+              abortController.signal.removeEventListener('abort', abortHandler)
+            }
+          }
+          // We dispatch the result action _after_ the catch, to avoid having any errors
+          // here get swallowed by the try/catch block,
+          // per https://twitter.com/dan_abramov/status/770914221638942720
+          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks
+
+          const skipDispatch =
+            options &&
+            !options.dispatchConditionRejection &&
+            rejected.match(finalAction) &&
+            (finalAction as any).meta.condition
+
+          if (!skipDispatch) {
+            dispatch(finalAction as any)
+          }
+          return finalAction
+        })()
+        return Object.assign(promise as SafePromise<any>, {
+          abort,
+          requestId,
+          arg,
+          unwrap() {
+            return promise.then<any>(unwrapResult)
+          },
+        })
+      }
+    }
+
+    return Object.assign(
+      actionCreator as AsyncThunkActionCreator<
+        Returned,
+        ThunkArg,
+        ThunkApiConfig
+      >,
+      {
+        pending,
+        rejected,
+        fulfilled,
+        settled: isAnyOf(rejected, fulfilled),
+        typePrefix,
+      },
+    )
+  }
+  createAsyncThunk.withTypes = () => createAsyncThunk
+
+  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>
+})()
+
+interface UnwrappableAction {
+  payload: any
+  meta?: any
+  error?: any
+}
+
+type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<
+  T,
+  { error: any }
+>['payload']
+
+/**
+ * @public
+ */
+export function unwrapResult<R extends UnwrappableAction>(
+  action: R,
+): UnwrappedActionPayload<R> {
+  if (action.meta && action.meta.rejectedWithValue) {
+    throw action.payload
+  }
+  if (action.error) {
+    throw action.error
+  }
+  return action.payload
+}
+
+type WithStrictNullChecks<True, False> = undefined extends boolean
+  ? False
+  : True
+
+function isThenable(value: any): value is PromiseLike<any> {
+  return (
+    value !== null &&
+    typeof value === 'object' &&
+    typeof value.then === 'function'
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,30 @@
+import { current, isDraft } from './immerImports'
+import { createSelectorCreator, weakMapMemoize } from './reselectImports'
+
+export const createDraftSafeSelectorCreator: typeof createSelectorCreator = (
+  ...args: unknown[]
+) => {
+  const createSelector = (createSelectorCreator as any)(...args)
+  const createDraftSafeSelector = Object.assign(
+    (...args: unknown[]) => {
+      const selector = createSelector(...args)
+      const wrappedSelector = (value: unknown, ...rest: unknown[]) =>
+        selector(isDraft(value) ? current(value) : value, ...rest)
+      Object.assign(wrappedSelector, selector)
+      return wrappedSelector as any
+    },
+    { withTypes: () => createDraftSafeSelector },
+  )
+  return createDraftSafeSelector
+}
+
+/**
+ * "Draft-Safe" version of `reselect`'s `createSelector`:
+ * If an `immer`-drafted object is passed into the resulting selector's first argument,
+ * the selector will act on the current draft value, instead of returning a cached value
+ * that might be possibly outdated if the draft has been modified since.
+ * @public
+ */
+export const createDraftSafeSelector =
+  /* @__PURE__ */
+  createDraftSafeSelectorCreator(weakMapMemoize)
Index: node_modules/@reduxjs/toolkit/src/createReducer.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createReducer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createReducer.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,226 @@
+import type { Draft } from 'immer'
+import {
+  createNextState,
+  isDraft,
+  isDraftable,
+  setUseStrictIteration,
+} from './immerImports'
+import type { Action, Reducer, UnknownAction } from 'redux'
+import type { ActionReducerMapBuilder } from './mapBuilders'
+import { executeReducerBuilderCallback } from './mapBuilders'
+import type { NoInfer, TypeGuard } from './tsHelpers'
+import { freezeDraftable } from './utils'
+
+/**
+ * Defines a mapping from action types to corresponding action object shapes.
+ *
+ * @deprecated This should not be used manually - it is only used for internal
+ *             inference purposes and should not have any further value.
+ *             It might be removed in the future.
+ * @public
+ */
+export type Actions<T extends keyof any = string> = Record<T, Action>
+
+export type ActionMatcherDescription<S, A extends Action> = {
+  matcher: TypeGuard<A>
+  reducer: CaseReducer<S, NoInfer<A>>
+}
+
+export type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<
+  ActionMatcherDescription<S, any>
+>
+
+export type ActionMatcherDescriptionCollection<S> = Array<
+  ActionMatcherDescription<S, any>
+>
+
+/**
+ * A *case reducer* is a reducer function for a specific action type. Case
+ * reducers can be composed to full reducers using `createReducer()`.
+ *
+ * Unlike a normal Redux reducer, a case reducer is never called with an
+ * `undefined` state to determine the initial state. Instead, the initial
+ * state is explicitly specified as an argument to `createReducer()`.
+ *
+ * In addition, a case reducer can choose to mutate the passed-in `state`
+ * value directly instead of returning a new state. This does not actually
+ * cause the store state to be mutated directly; instead, thanks to
+ * [immer](https://github.com/mweststrate/immer), the mutations are
+ * translated to copy operations that result in a new state.
+ *
+ * @public
+ */
+export type CaseReducer<S = any, A extends Action = UnknownAction> = (
+  state: Draft<S>,
+  action: A,
+) => NoInfer<S> | void | Draft<NoInfer<S>>
+
+/**
+ * A mapping from action types to case reducers for `createReducer()`.
+ *
+ * @deprecated This should not be used manually - it is only used
+ *             for internal inference purposes and using it manually
+ *             would lead to type erasure.
+ *             It might be removed in the future.
+ * @public
+ */
+export type CaseReducers<S, AS extends Actions> = {
+  [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void
+}
+
+export type NotFunction<T> = T extends Function ? never : T
+
+function isStateFunction<S>(x: unknown): x is () => S {
+  return typeof x === 'function'
+}
+
+export type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
+  getInitialState: () => S
+}
+
+/**
+ * A utility function that allows defining a reducer as a mapping from action
+ * type to *case reducer* functions that handle these action types. The
+ * reducer's initial state is passed as the first argument.
+ *
+ * @remarks
+ * The body of every case reducer is implicitly wrapped with a call to
+ * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
+ * This means that rather than returning a new state object, you can also
+ * mutate the passed-in state object directly; these mutations will then be
+ * automatically and efficiently translated into copies, giving you both
+ * convenience and immutability.
+ *
+ * @overloadSummary
+ * This function accepts a callback that receives a `builder` object as its argument.
+ * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
+ * called to define what actions this reducer will handle.
+ *
+ * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+ * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
+ *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+ * @example
+```ts
+import {
+  createAction,
+  createReducer,
+  UnknownAction,
+  PayloadAction,
+} from "@reduxjs/toolkit";
+
+const increment = createAction<number>("increment");
+const decrement = createAction<number>("decrement");
+
+function isActionWithNumberPayload(
+  action: UnknownAction
+): action is PayloadAction<number> {
+  return typeof action.payload === "number";
+}
+
+const reducer = createReducer(
+  {
+    counter: 0,
+    sumOfNumberPayloads: 0,
+    unhandledActions: 0,
+  },
+  (builder) => {
+    builder
+      .addCase(increment, (state, action) => {
+        // action is inferred correctly here
+        state.counter += action.payload;
+      })
+      // You can chain calls, or have separate `builder.addCase()` lines each time
+      .addCase(decrement, (state, action) => {
+        state.counter -= action.payload;
+      })
+      // You can apply a "matcher function" to incoming actions
+      .addMatcher(isActionWithNumberPayload, (state, action) => {})
+      // and provide a default case if no other handlers matched
+      .addDefaultCase((state, action) => {});
+  }
+);
+```
+ * @public
+ */
+export function createReducer<S extends NotFunction<any>>(
+  initialState: S | (() => S),
+  mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void,
+): ReducerWithInitialState<S> {
+  if (process.env.NODE_ENV !== 'production') {
+    if (typeof mapOrBuilderCallback === 'object') {
+      throw new Error(
+        "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer",
+      )
+    }
+  }
+
+  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =
+    executeReducerBuilderCallback(mapOrBuilderCallback)
+
+  // Ensure the initial state gets frozen either way (if draftable)
+  let getInitialState: () => S
+  if (isStateFunction(initialState)) {
+    getInitialState = () => freezeDraftable(initialState())
+  } else {
+    const frozenInitialState = freezeDraftable(initialState)
+    getInitialState = () => frozenInitialState
+  }
+
+  function reducer(state = getInitialState(), action: any): S {
+    let caseReducers = [
+      actionsMap[action.type],
+      ...finalActionMatchers
+        .filter(({ matcher }) => matcher(action))
+        .map(({ reducer }) => reducer),
+    ]
+    if (caseReducers.filter((cr) => !!cr).length === 0) {
+      caseReducers = [finalDefaultCaseReducer]
+    }
+
+    return caseReducers.reduce((previousState, caseReducer): S => {
+      if (caseReducer) {
+        if (isDraft(previousState)) {
+          // If it's already a draft, we must already be inside a `createNextState` call,
+          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested
+          // inside an existing draft. It's safe to just pass the draft to the mutator.
+          const draft = previousState as Draft<S> // We can assume this is already a draft
+          const result = caseReducer(draft, action)
+
+          if (result === undefined) {
+            return previousState
+          }
+
+          return result as S
+        } else if (!isDraftable(previousState)) {
+          // If state is not draftable (ex: a primitive, such as 0), we want to directly
+          // return the caseReducer func and not wrap it with produce.
+          const result = caseReducer(previousState as any, action)
+
+          if (result === undefined) {
+            if (previousState === null) {
+              return previousState
+            }
+            throw Error(
+              'A case reducer on a non-draftable value must not return undefined',
+            )
+          }
+
+          return result as S
+        } else {
+          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather
+          // than an Immutable<S>, and TypeScript cannot find out how to reconcile
+          // these two types.
+          return createNextState(previousState, (draft: Draft<S>) => {
+            return caseReducer(draft, action)
+          })
+        }
+      }
+
+      return previousState
+    }, state)
+  }
+
+  reducer.getInitialState = getInitialState
+
+  return reducer as ReducerWithInitialState<S>
+}
Index: node_modules/@reduxjs/toolkit/src/createSlice.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/createSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/createSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1073 @@
+import type { Action, Reducer, UnknownAction } from 'redux'
+import type { Selector } from 'reselect'
+import type { InjectConfig } from './combineSlices'
+import type {
+  ActionCreatorWithoutPayload,
+  PayloadAction,
+  PayloadActionCreator,
+  PrepareAction,
+  _ActionCreatorWithPreparedPayload,
+} from './createAction'
+import { createAction } from './createAction'
+import type {
+  AsyncThunk,
+  AsyncThunkConfig,
+  AsyncThunkOptions,
+  AsyncThunkPayloadCreator,
+  OverrideThunkApiConfigs,
+} from './createAsyncThunk'
+import { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk'
+import type {
+  ActionMatcherDescriptionCollection,
+  CaseReducer,
+  ReducerWithInitialState,
+} from './createReducer'
+import { createReducer } from './createReducer'
+import type {
+  ActionReducerMapBuilder,
+  AsyncThunkReducers,
+  TypedActionCreator,
+} from './mapBuilders'
+import { executeReducerBuilderCallback } from './mapBuilders'
+import type { Id, TypeGuard } from './tsHelpers'
+import { getOrInsertComputed } from './utils'
+
+const asyncThunkSymbol = /* @__PURE__ */ Symbol.for(
+  'rtk-slice-createasyncthunk',
+)
+// type is annotated because it's too long to infer
+export const asyncThunkCreator: {
+  [asyncThunkSymbol]: typeof _createAsyncThunk
+} = {
+  [asyncThunkSymbol]: _createAsyncThunk,
+}
+
+type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
+  reducerPath?: NewReducerPath
+}
+
+/**
+ * The return value of `createSlice`
+ *
+ * @public
+ */
+export interface Slice<
+  State = any,
+  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
+  Name extends string = string,
+  ReducerPath extends string = Name,
+  Selectors extends SliceSelectors<State> = SliceSelectors<State>,
+> {
+  /**
+   * The slice name.
+   */
+  name: Name
+
+  /**
+   *  The slice reducer path.
+   */
+  reducerPath: ReducerPath
+
+  /**
+   * The slice's reducer.
+   */
+  reducer: Reducer<State>
+
+  /**
+   * Action creators for the types of actions that are handled by the slice
+   * reducer.
+   */
+  actions: CaseReducerActions<CaseReducers, Name>
+
+  /**
+   * The individual case reducer functions that were passed in the `reducers` parameter.
+   * This enables reuse and testing if they were defined inline when calling `createSlice`.
+   */
+  caseReducers: SliceDefinedCaseReducers<CaseReducers>
+
+  /**
+   * Provides access to the initial state value given to the slice.
+   * If a lazy state initializer was provided, it will be called and a fresh value returned.
+   */
+  getInitialState: () => State
+
+  /**
+   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+   */
+  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>
+
+  /**
+   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+   */
+  getSelectors<RootState>(
+    selectState: (rootState: RootState) => State,
+  ): Id<SliceDefinedSelectors<State, Selectors, RootState>>
+
+  /**
+   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
+   *
+   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
+   */
+  get selectors(): Id<
+    SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>
+  >
+
+  /**
+   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
+   */
+  injectInto<NewReducerPath extends string = ReducerPath>(
+    this: this,
+    injectable: {
+      inject: (
+        slice: { reducerPath: string; reducer: Reducer },
+        config?: InjectConfig,
+      ) => void
+    },
+    config?: InjectIntoConfig<NewReducerPath>,
+  ): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>
+
+  /**
+   * Select the slice state, using the slice's current reducerPath.
+   *
+   * Will throw an error if slice is not found.
+   */
+  selectSlice(state: { [K in ReducerPath]: State }): State
+}
+
+/**
+ * A slice after being called with `injectInto(reducer)`.
+ *
+ * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
+ */
+type InjectedSlice<
+  State = any,
+  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
+  Name extends string = string,
+  ReducerPath extends string = Name,
+  Selectors extends SliceSelectors<State> = SliceSelectors<State>,
+> = Omit<
+  Slice<State, CaseReducers, Name, ReducerPath, Selectors>,
+  'getSelectors' | 'selectors'
+> & {
+  /**
+   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
+   */
+  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>
+
+  /**
+   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
+   */
+  getSelectors<RootState>(
+    selectState: (rootState: RootState) => State | undefined,
+  ): Id<SliceDefinedSelectors<State, Selectors, RootState>>
+
+  /**
+   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
+   *
+   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
+   */
+  get selectors(): Id<
+    SliceDefinedSelectors<
+      State,
+      Selectors,
+      { [K in ReducerPath]?: State | undefined }
+    >
+  >
+
+  /**
+   * Select the slice state, using the slice's current reducerPath.
+   *
+   * Returns initial state if slice is not found.
+   */
+  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State
+}
+
+/**
+ * Options for `createSlice()`.
+ *
+ * @public
+ */
+export interface CreateSliceOptions<
+  State = any,
+  CR extends SliceCaseReducers<State> = SliceCaseReducers<State>,
+  Name extends string = string,
+  ReducerPath extends string = Name,
+  Selectors extends SliceSelectors<State> = SliceSelectors<State>,
+> {
+  /**
+   * The slice's name. Used to namespace the generated action types.
+   */
+  name: Name
+
+  /**
+   * The slice's reducer path. Used when injecting into a combined slice reducer.
+   */
+  reducerPath?: ReducerPath
+
+  /**
+   * The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
+   */
+  initialState: State | (() => State)
+
+  /**
+   * A mapping from action types to action-type-specific *case reducer*
+   * functions. For every action type, a matching action creator will be
+   * generated using `createAction()`.
+   */
+  reducers:
+    | ValidateSliceCaseReducers<State, CR>
+    | ((creators: ReducerCreators<State>) => CR)
+
+  /**
+   * A callback that receives a *builder* object to define
+   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
+   *
+   *
+   * @example
+```ts
+import { createAction, createSlice, Action } from '@reduxjs/toolkit'
+const incrementBy = createAction<number>('incrementBy')
+const decrement = createAction('decrement')
+
+interface RejectedAction extends Action {
+  error: Error
+}
+
+function isRejectedAction(action: Action): action is RejectedAction {
+  return action.type.endsWith('rejected')
+}
+
+createSlice({
+  name: 'counter',
+  initialState: 0,
+  reducers: {},
+  extraReducers: builder => {
+    builder
+      .addCase(incrementBy, (state, action) => {
+        // action is inferred correctly here if using TS
+      })
+      // You can chain calls, or have separate `builder.addCase()` lines each time
+      .addCase(decrement, (state, action) => {})
+      // You can match a range of action types
+      .addMatcher(
+        isRejectedAction,
+        // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
+        (state, action) => {}
+      )
+      // and provide a default case if no other handlers matched
+      .addDefaultCase((state, action) => {})
+    }
+})
+```
+   */
+  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void
+
+  /**
+   * A map of selectors that receive the slice's state and any additional arguments, and return a result.
+   */
+  selectors?: Selectors
+}
+
+export enum ReducerType {
+  reducer = 'reducer',
+  reducerWithPrepare = 'reducerWithPrepare',
+  asyncThunk = 'asyncThunk',
+}
+
+type ReducerDefinition<T extends ReducerType = ReducerType> = {
+  _reducerDefinitionType: T
+}
+
+export type CaseReducerDefinition<
+  S = any,
+  A extends Action = UnknownAction,
+> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>
+
+/**
+ * A CaseReducer with a `prepare` method.
+ *
+ * @public
+ */
+export type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
+  reducer: CaseReducer<State, Action>
+  prepare: PrepareAction<Action['payload']>
+}
+
+export interface CaseReducerWithPrepareDefinition<
+  State,
+  Action extends PayloadAction,
+> extends CaseReducerWithPrepare<State, Action>,
+    ReducerDefinition<ReducerType.reducerWithPrepare> {}
+
+type AsyncThunkSliceReducerConfig<
+  State,
+  ThunkArg extends any,
+  Returned = unknown,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
+  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>
+}
+
+type AsyncThunkSliceReducerDefinition<
+  State,
+  ThunkArg extends any,
+  Returned = unknown,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> &
+  ReducerDefinition<ReducerType.asyncThunk> & {
+    payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>
+  }
+
+/**
+ * Providing these as part of the config would cause circular types, so we disallow passing them
+ */
+type PreventCircular<ThunkApiConfig> = {
+  [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch'
+    ? never
+    : ThunkApiConfig[K]
+}
+
+interface AsyncThunkCreator<
+  State,
+  CurriedThunkApiConfig extends
+    PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>,
+> {
+  <Returned, ThunkArg = void>(
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      CurriedThunkApiConfig
+    >,
+    config?: AsyncThunkSliceReducerConfig<
+      State,
+      ThunkArg,
+      Returned,
+      CurriedThunkApiConfig
+    >,
+  ): AsyncThunkSliceReducerDefinition<
+    State,
+    ThunkArg,
+    Returned,
+    CurriedThunkApiConfig
+  >
+  <
+    Returned,
+    ThunkArg,
+    ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {},
+  >(
+    payloadCreator: AsyncThunkPayloadCreator<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig
+    >,
+    config?: AsyncThunkSliceReducerConfig<
+      State,
+      ThunkArg,
+      Returned,
+      ThunkApiConfig
+    >,
+  ): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>
+  withTypes<
+    ThunkApiConfig extends PreventCircular<AsyncThunkConfig>,
+  >(): AsyncThunkCreator<
+    State,
+    OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
+  >
+}
+
+export interface ReducerCreators<State> {
+  reducer(
+    caseReducer: CaseReducer<State, PayloadAction>,
+  ): CaseReducerDefinition<State, PayloadAction>
+  reducer<Payload>(
+    caseReducer: CaseReducer<State, PayloadAction<Payload>>,
+  ): CaseReducerDefinition<State, PayloadAction<Payload>>
+
+  asyncThunk: AsyncThunkCreator<State>
+
+  preparedReducer<Prepare extends PrepareAction<any>>(
+    prepare: Prepare,
+    reducer: CaseReducer<
+      State,
+      ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>
+    >,
+  ): {
+    _reducerDefinitionType: ReducerType.reducerWithPrepare
+    prepare: Prepare
+    reducer: CaseReducer<
+      State,
+      ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>
+    >
+  }
+}
+
+/**
+ * The type describing a slice's `reducers` option.
+ *
+ * @public
+ */
+export type SliceCaseReducers<State> =
+  | Record<string, ReducerDefinition>
+  | Record<
+      string,
+      | CaseReducer<State, PayloadAction<any>>
+      | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>
+    >
+
+/**
+ * The type describing a slice's `selectors` option.
+ */
+export type SliceSelectors<State> = {
+  [K: string]: (sliceState: State, ...args: any[]) => any
+}
+
+type SliceActionType<
+  SliceName extends string,
+  ActionName extends keyof any,
+> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string
+
+/**
+ * Derives the slice's `actions` property from the `reducers` options
+ *
+ * @public
+ */
+export type CaseReducerActions<
+  CaseReducers extends SliceCaseReducers<any>,
+  SliceName extends string,
+> = {
+  [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition
+    ? Definition extends { prepare: any }
+      ? ActionCreatorForCaseReducerWithPrepare<
+          Definition,
+          SliceActionType<SliceName, Type>
+        >
+      : Definition extends AsyncThunkSliceReducerDefinition<
+            any,
+            infer ThunkArg,
+            infer Returned,
+            infer ThunkApiConfig
+          >
+        ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig>
+        : Definition extends { reducer: any }
+          ? ActionCreatorForCaseReducer<
+              Definition['reducer'],
+              SliceActionType<SliceName, Type>
+            >
+          : ActionCreatorForCaseReducer<
+              Definition,
+              SliceActionType<SliceName, Type>
+            >
+    : never
+}
+
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducerWithPrepare<
+  CR extends { prepare: any },
+  Type extends string,
+> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>
+
+/**
+ * Get a `PayloadActionCreator` type for a passed `CaseReducer`
+ *
+ * @internal
+ */
+type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (
+  state: any,
+  action: infer Action,
+) => any
+  ? Action extends { payload: infer P }
+    ? PayloadActionCreator<P, Type>
+    : ActionCreatorWithoutPayload<Type>
+  : ActionCreatorWithoutPayload<Type>
+
+/**
+ * Extracts the CaseReducers out of a `reducers` object, even if they are
+ * tested into a `CaseReducerWithPrepare`.
+ *
+ * @internal
+ */
+type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
+  [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition
+    ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any>
+      ? Id<
+          Pick<
+            Required<Definition>,
+            'fulfilled' | 'rejected' | 'pending' | 'settled'
+          >
+        >
+      : Definition extends {
+            reducer: infer Reducer
+          }
+        ? Reducer
+        : Definition
+    : never
+}
+
+type RemappedSelector<S extends Selector, NewState> =
+  S extends Selector<any, infer R, infer P>
+    ? Selector<NewState, R, P> & { unwrapped: S }
+    : never
+
+/**
+ * Extracts the final selector type from the `selectors` object.
+ *
+ * Removes the `string` index signature from the default value.
+ */
+type SliceDefinedSelectors<
+  State,
+  Selectors extends SliceSelectors<State>,
+  RootState,
+> = {
+  [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<
+    Selectors[K],
+    RootState
+  >
+}
+
+/**
+ * Used on a SliceCaseReducers object.
+ * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
+ * the `reducer` and the `prepare` function use the same type of `payload`.
+ *
+ * Might do additional such checks in the future.
+ *
+ * This type is only ever useful if you want to write your own wrapper around
+ * `createSlice`. Please don't use it otherwise!
+ *
+ * @public
+ */
+export type ValidateSliceCaseReducers<
+  S,
+  ACR extends SliceCaseReducers<S>,
+> = ACR & {
+  [T in keyof ACR]: ACR[T] extends {
+    reducer(s: S, action?: infer A): any
+  }
+    ? {
+        prepare(...a: never[]): Omit<A, 'type'>
+      }
+    : {}
+}
+
+function getType(slice: string, actionKey: string): string {
+  return `${slice}/${actionKey}`
+}
+
+interface BuildCreateSliceConfig {
+  creators?: {
+    asyncThunk?: typeof asyncThunkCreator
+  }
+}
+
+export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
+  const cAT = creators?.asyncThunk?.[asyncThunkSymbol]
+  return function createSlice<
+    State,
+    CaseReducers extends SliceCaseReducers<State>,
+    Name extends string,
+    Selectors extends SliceSelectors<State>,
+    ReducerPath extends string = Name,
+  >(
+    options: CreateSliceOptions<
+      State,
+      CaseReducers,
+      Name,
+      ReducerPath,
+      Selectors
+    >,
+  ): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {
+    const { name, reducerPath = name as unknown as ReducerPath } = options
+    if (!name) {
+      throw new Error('`name` is a required option for createSlice')
+    }
+
+    if (
+      typeof process !== 'undefined' &&
+      process.env.NODE_ENV === 'development'
+    ) {
+      if (options.initialState === undefined) {
+        console.error(
+          'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',
+        )
+      }
+    }
+
+    const reducers =
+      (typeof options.reducers === 'function'
+        ? options.reducers(buildReducerCreators<State>())
+        : options.reducers) || {}
+
+    const reducerNames = Object.keys(reducers)
+
+    const context: ReducerHandlingContext<State> = {
+      sliceCaseReducersByName: {},
+      sliceCaseReducersByType: {},
+      actionCreators: {},
+      sliceMatchers: [],
+    }
+
+    const contextMethods: ReducerHandlingContextMethods<State> = {
+      addCase(
+        typeOrActionCreator: string | TypedActionCreator<any>,
+        reducer: CaseReducer<State>,
+      ) {
+        const type =
+          typeof typeOrActionCreator === 'string'
+            ? typeOrActionCreator
+            : typeOrActionCreator.type
+        if (!type) {
+          throw new Error(
+            '`context.addCase` cannot be called with an empty action type',
+          )
+        }
+        if (type in context.sliceCaseReducersByType) {
+          throw new Error(
+            '`context.addCase` cannot be called with two reducers for the same action type: ' +
+              type,
+          )
+        }
+        context.sliceCaseReducersByType[type] = reducer
+        return contextMethods
+      },
+      addMatcher(matcher, reducer) {
+        context.sliceMatchers.push({ matcher, reducer })
+        return contextMethods
+      },
+      exposeAction(name, actionCreator) {
+        context.actionCreators[name] = actionCreator
+        return contextMethods
+      },
+      exposeCaseReducer(name, reducer) {
+        context.sliceCaseReducersByName[name] = reducer
+        return contextMethods
+      },
+    }
+
+    reducerNames.forEach((reducerName) => {
+      const reducerDefinition = reducers[reducerName]
+      const reducerDetails: ReducerDetails = {
+        reducerName,
+        type: getType(name, reducerName),
+        createNotation: typeof options.reducers === 'function',
+      }
+      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {
+        handleThunkCaseReducerDefinition(
+          reducerDetails,
+          reducerDefinition,
+          contextMethods,
+          cAT,
+        )
+      } else {
+        handleNormalReducerDefinition<State>(
+          reducerDetails,
+          reducerDefinition as any,
+          contextMethods,
+        )
+      }
+    })
+
+    function buildReducer() {
+      if (process.env.NODE_ENV !== 'production') {
+        if (typeof options.extraReducers === 'object') {
+          throw new Error(
+            "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice",
+          )
+        }
+      }
+      const [
+        extraReducers = {},
+        actionMatchers = [],
+        defaultCaseReducer = undefined,
+      ] =
+        typeof options.extraReducers === 'function'
+          ? executeReducerBuilderCallback(options.extraReducers)
+          : [options.extraReducers]
+
+      const finalCaseReducers = {
+        ...extraReducers,
+        ...context.sliceCaseReducersByType,
+      }
+
+      return createReducer(options.initialState, (builder) => {
+        for (let key in finalCaseReducers) {
+          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>)
+        }
+        for (let sM of context.sliceMatchers) {
+          builder.addMatcher(sM.matcher, sM.reducer)
+        }
+        for (let m of actionMatchers) {
+          builder.addMatcher(m.matcher, m.reducer)
+        }
+        if (defaultCaseReducer) {
+          builder.addDefaultCase(defaultCaseReducer)
+        }
+      })
+    }
+
+    const selectSelf = (state: State) => state
+
+    const injectedSelectorCache = new Map<
+      boolean,
+      WeakMap<
+        (rootState: any) => State | undefined,
+        Record<string, (rootState: any) => any>
+      >
+    >()
+
+    const injectedStateCache = new WeakMap<(rootState: any) => State, State>()
+
+    let _reducer: ReducerWithInitialState<State>
+
+    function reducer(state: State | undefined, action: UnknownAction) {
+      if (!_reducer) _reducer = buildReducer()
+
+      return _reducer(state, action)
+    }
+
+    function getInitialState() {
+      if (!_reducer) _reducer = buildReducer()
+
+      return _reducer.getInitialState()
+    }
+
+    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(
+      reducerPath: CurrentReducerPath,
+      injected = false,
+    ): Pick<
+      Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>,
+      'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'
+    > {
+      function selectSlice(state: { [K in CurrentReducerPath]: State }) {
+        let sliceState = state[reducerPath]
+        if (typeof sliceState === 'undefined') {
+          if (injected) {
+            sliceState = getOrInsertComputed(
+              injectedStateCache,
+              selectSlice,
+              getInitialState,
+            )
+          } else if (process.env.NODE_ENV !== 'production') {
+            throw new Error(
+              'selectSlice returned undefined for an uninjected slice reducer',
+            )
+          }
+        }
+        return sliceState
+      }
+
+      function getSelectors(
+        selectState: (rootState: any) => State = selectSelf,
+      ) {
+        const selectorCache = getOrInsertComputed(
+          injectedSelectorCache,
+          injected,
+          () => new WeakMap(),
+        )
+
+        return getOrInsertComputed(selectorCache, selectState, () => {
+          const map: Record<string, Selector<any, any>> = {}
+          for (const [name, selector] of Object.entries(
+            options.selectors ?? {},
+          )) {
+            map[name] = wrapSelector(
+              selector,
+              selectState,
+              () =>
+                getOrInsertComputed(
+                  injectedStateCache,
+                  selectState,
+                  getInitialState,
+                ),
+              injected,
+            )
+          }
+          return map
+        }) as any
+      }
+      return {
+        reducerPath,
+        getSelectors,
+        get selectors() {
+          return getSelectors(selectSlice)
+        },
+        selectSlice,
+      }
+    }
+
+    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {
+      name,
+      reducer,
+      actions: context.actionCreators as any,
+      caseReducers: context.sliceCaseReducersByName as any,
+      getInitialState,
+      ...makeSelectorProps(reducerPath),
+      injectInto(injectable, { reducerPath: pathOpt, ...config } = {}) {
+        const newReducerPath = pathOpt ?? reducerPath
+        injectable.inject({ reducerPath: newReducerPath, reducer }, config)
+        return {
+          ...slice,
+          ...makeSelectorProps(newReducerPath, true),
+        } as any
+      },
+    }
+    return slice
+  }
+}
+
+function wrapSelector<State, NewState, S extends Selector<State>>(
+  selector: S,
+  selectState: Selector<NewState, State>,
+  getInitialState: () => State,
+  injected?: boolean,
+) {
+  function wrapper(rootState: NewState, ...args: any[]) {
+    let sliceState = selectState(rootState)
+    if (typeof sliceState === 'undefined') {
+      if (injected) {
+        sliceState = getInitialState()
+      } else if (process.env.NODE_ENV !== 'production') {
+        throw new Error(
+          'selectState returned undefined for an uninjected slice reducer',
+        )
+      }
+    }
+    return selector(sliceState, ...args)
+  }
+  wrapper.unwrapped = selector
+  return wrapper as RemappedSelector<S, NewState>
+}
+
+/**
+ * A function that accepts an initial state, an object full of reducer
+ * functions, and a "slice name", and automatically generates
+ * action creators and action types that correspond to the
+ * reducers and state.
+ *
+ * @public
+ */
+export const createSlice = /* @__PURE__ */ buildCreateSlice()
+
+interface ReducerHandlingContext<State> {
+  sliceCaseReducersByName: Record<
+    string,
+    | CaseReducer<State, any>
+    | Pick<
+        AsyncThunkSliceReducerDefinition<State, any, any, any>,
+        'fulfilled' | 'rejected' | 'pending' | 'settled'
+      >
+  >
+  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>
+  sliceMatchers: ActionMatcherDescriptionCollection<State>
+  actionCreators: Record<string, Function>
+}
+
+interface ReducerHandlingContextMethods<State> {
+  /**
+   * Adds a case reducer to handle a single action type.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<ActionCreator extends TypedActionCreator<string>>(
+    actionCreator: ActionCreator,
+    reducer: CaseReducer<State, ReturnType<ActionCreator>>,
+  ): ReducerHandlingContextMethods<State>
+  /**
+   * Adds a case reducer to handle a single action type.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<Type extends string, A extends Action<Type>>(
+    type: Type,
+    reducer: CaseReducer<State, A>,
+  ): ReducerHandlingContextMethods<State>
+
+  /**
+   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.
+   * @remarks
+   * If multiple matcher reducers match, all of them will be executed in the order
+   * they were defined in - even if a case reducer already matched.
+   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.
+   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
+   *   function
+   * @param reducer - The actual case reducer function.
+   *
+   */
+  addMatcher<A>(
+    matcher: TypeGuard<A>,
+    reducer: CaseReducer<State, A extends Action ? A : A & Action>,
+  ): ReducerHandlingContextMethods<State>
+  /**
+   * Add an action to be exposed under the final `slice.actions` key.
+   * @param name The key to be exposed as.
+   * @param actionCreator The action to expose.
+   * @example
+   * context.exposeAction("addPost", createAction<Post>("addPost"));
+   *
+   * export const { addPost } = slice.actions
+   *
+   * dispatch(addPost(post))
+   */
+  exposeAction(
+    name: string,
+    actionCreator: Function,
+  ): ReducerHandlingContextMethods<State>
+  /**
+   * Add a case reducer to be exposed under the final `slice.caseReducers` key.
+   * @param name The key to be exposed as.
+   * @param reducer The reducer to expose.
+   * @example
+   * context.exposeCaseReducer("addPost", (state, action: PayloadAction<Post>) => {
+   *   state.push(action.payload)
+   * })
+   *
+   * slice.caseReducers.addPost([], addPost(post))
+   */
+  exposeCaseReducer(
+    name: string,
+    reducer:
+      | CaseReducer<State, any>
+      | Pick<
+          AsyncThunkSliceReducerDefinition<State, any, any, any>,
+          'fulfilled' | 'rejected' | 'pending' | 'settled'
+        >,
+  ): ReducerHandlingContextMethods<State>
+}
+
+interface ReducerDetails {
+  /** The key the reducer was defined under */
+  reducerName: string
+  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */
+  type: string
+  /** Whether create. notation was used when defining reducers */
+  createNotation: boolean
+}
+
+function buildReducerCreators<State>(): ReducerCreators<State> {
+  function asyncThunk(
+    payloadCreator: AsyncThunkPayloadCreator<any, any>,
+    config: AsyncThunkSliceReducerConfig<State, any>,
+  ): AsyncThunkSliceReducerDefinition<State, any> {
+    return {
+      _reducerDefinitionType: ReducerType.asyncThunk,
+      payloadCreator,
+      ...config,
+    }
+  }
+  asyncThunk.withTypes = () => asyncThunk
+  return {
+    reducer(caseReducer: CaseReducer<State, any>) {
+      return Object.assign(
+        {
+          // hack so the wrapping function has the same name as the original
+          // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
+          [caseReducer.name](...args: Parameters<typeof caseReducer>) {
+            return caseReducer(...args)
+          },
+        }[caseReducer.name],
+        {
+          _reducerDefinitionType: ReducerType.reducer,
+        } as const,
+      )
+    },
+    preparedReducer(prepare, reducer) {
+      return {
+        _reducerDefinitionType: ReducerType.reducerWithPrepare,
+        prepare,
+        reducer,
+      }
+    },
+    asyncThunk: asyncThunk as any,
+  }
+}
+
+function handleNormalReducerDefinition<State>(
+  { type, reducerName, createNotation }: ReducerDetails,
+  maybeReducerWithPrepare:
+    | CaseReducer<State, { payload: any; type: string }>
+    | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>,
+  context: ReducerHandlingContextMethods<State>,
+) {
+  let caseReducer: CaseReducer<State, any>
+  let prepareCallback: PrepareAction<any> | undefined
+  if ('reducer' in maybeReducerWithPrepare) {
+    if (
+      createNotation &&
+      !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)
+    ) {
+      throw new Error(
+        'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.',
+      )
+    }
+    caseReducer = maybeReducerWithPrepare.reducer
+    prepareCallback = maybeReducerWithPrepare.prepare
+  } else {
+    caseReducer = maybeReducerWithPrepare
+  }
+  context
+    .addCase(type, caseReducer)
+    .exposeCaseReducer(reducerName, caseReducer)
+    .exposeAction(
+      reducerName,
+      prepareCallback
+        ? createAction(type, prepareCallback)
+        : createAction(type),
+    )
+}
+
+function isAsyncThunkSliceReducerDefinition<State>(
+  reducerDefinition: any,
+): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {
+  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk
+}
+
+function isCaseReducerWithPrepareDefinition<State>(
+  reducerDefinition: any,
+): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {
+  return (
+    reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare
+  )
+}
+
+function handleThunkCaseReducerDefinition<State>(
+  { type, reducerName }: ReducerDetails,
+  reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>,
+  context: ReducerHandlingContextMethods<State>,
+  cAT: typeof _createAsyncThunk | undefined,
+) {
+  if (!cAT) {
+    throw new Error(
+      'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' +
+        'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.',
+    )
+  }
+  const { payloadCreator, fulfilled, pending, rejected, settled, options } =
+    reducerDefinition
+  const thunk = cAT(type, payloadCreator, options as any)
+  context.exposeAction(reducerName, thunk)
+
+  if (fulfilled) {
+    context.addCase(thunk.fulfilled, fulfilled)
+  }
+  if (pending) {
+    context.addCase(thunk.pending, pending)
+  }
+  if (rejected) {
+    context.addCase(thunk.rejected, rejected)
+  }
+  if (settled) {
+    context.addMatcher(thunk.settled, settled)
+  }
+
+  context.exposeCaseReducer(reducerName, {
+    fulfilled: fulfilled || noop,
+    pending: pending || noop,
+    rejected: rejected || noop,
+    settled: settled || noop,
+  })
+}
+
+function noop() {}
Index: node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,241 @@
+import type { Action, ActionCreator, StoreEnhancer } from 'redux'
+import { compose } from './reduxImports'
+
+/**
+ * @public
+ */
+export interface DevToolsEnhancerOptions {
+  /**
+   * the instance name to be showed on the monitor page. Default value is `document.title`.
+   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
+   */
+  name?: string
+  /**
+   * action creators functions to be available in the Dispatcher.
+   */
+  actionCreators?: ActionCreator<any>[] | { [key: string]: ActionCreator<any> }
+  /**
+   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
+   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
+   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
+   *
+   * @default 500 ms.
+   */
+  latency?: number
+  /**
+   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
+   *
+   * @default 50
+   */
+  maxAge?: number
+  /**
+   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
+   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
+   * functions.
+   */
+  serialize?:
+    | boolean
+    | {
+        /**
+         * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
+         * - `false` - will handle also circular references.
+         * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
+         * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
+         *   For each of them you can indicate if to include (by setting as `true`).
+         *   For `function` key you can also specify a custom function which handles serialization.
+         *   See [`jsan`](https://github.com/kolodny/jsan) for more details.
+         */
+        options?:
+          | undefined
+          | boolean
+          | {
+              date?: true
+              regex?: true
+              undefined?: true
+              error?: true
+              symbol?: true
+              map?: true
+              set?: true
+              function?: true | ((fn: (...args: any[]) => any) => string)
+            }
+        /**
+         * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
+         * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
+         * key. So you can deserialize it back while importing or persisting data.
+         * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
+         */
+        replacer?: (key: string, value: unknown) => any
+        /**
+         * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
+         * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
+         * as an example on how to serialize special data types and get them back.
+         */
+        reviver?: (key: string, value: unknown) => any
+        /**
+         * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
+         * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
+         * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
+         */
+        immutable?: any
+        /**
+         * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
+         */
+        refs?: any
+      }
+  /**
+   * function which takes `action` object and id number as arguments, and should return `action` object back.
+   */
+  actionSanitizer?: <A extends Action>(action: A, id: number) => A
+  /**
+   * function which takes `state` object and index as arguments, and should return `state` object back.
+   */
+  stateSanitizer?: <S>(state: S, index: number) => S
+  /**
+   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+   */
+  actionsDenylist?: string | string[]
+  /**
+   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
+   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
+   */
+  actionsAllowlist?: string | string[]
+  /**
+   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
+   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
+   */
+  predicate?: <S, A extends Action>(state: S, action: A) => boolean
+  /**
+   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.
+   * Available only for Redux enhancer, for others use `autoPause`.
+   *
+   * @default true
+   */
+  shouldRecordChanges?: boolean
+  /**
+   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
+   * If not specified, will commit when paused. Available only for Redux enhancer.
+   *
+   * @default "@@PAUSED""
+   */
+  pauseActionType?: string
+  /**
+   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
+   * Not available for Redux enhancer (as it already does it but storing the data to be sent).
+   *
+   * @default false
+   */
+  autoPause?: boolean
+  /**
+   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
+   * Available only for Redux enhancer.
+   *
+   * @default false
+   */
+  shouldStartLocked?: boolean
+  /**
+   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
+   *
+   * @default true
+   */
+  shouldHotReload?: boolean
+  /**
+   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
+   *
+   * @default false
+   */
+  shouldCatchErrors?: boolean
+  /**
+   * If you want to restrict the extension, specify the features you allow.
+   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
+   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
+   * Otherwise, you'll get/set the data right from the monitor part.
+   */
+  features?: {
+    /**
+     * start/pause recording of dispatched actions
+     */
+    pause?: boolean
+    /**
+     * lock/unlock dispatching actions and side effects
+     */
+    lock?: boolean
+    /**
+     * persist states on page reloading
+     */
+    persist?: boolean
+    /**
+     * export history of actions in a file
+     */
+    export?: boolean | 'custom'
+    /**
+     * import history of actions from a file
+     */
+    import?: boolean | 'custom'
+    /**
+     * jump back and forth (time travelling)
+     */
+    jump?: boolean
+    /**
+     * skip (cancel) actions
+     */
+    skip?: boolean
+    /**
+     * drag and drop actions in the history list
+     */
+    reorder?: boolean
+    /**
+     * dispatch custom actions or action creators
+     */
+    dispatch?: boolean
+    /**
+     * generate tests for the selected actions
+     */
+    test?: boolean
+  }
+  /**
+   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
+   * Defaults to false.
+   */
+  trace?: boolean | (<A extends Action>(action: A) => string)
+  /**
+   * The maximum number of stack trace entries to record per action. Defaults to 10.
+   */
+  traceLimit?: number
+}
+
+type Compose = typeof compose
+
+interface ComposeWithDevTools {
+  (options: DevToolsEnhancerOptions): Compose
+  <StoreExt extends {}>(
+    ...funcs: StoreEnhancer<StoreExt>[]
+  ): StoreEnhancer<StoreExt>
+}
+
+/**
+ * @public
+ */
+export const composeWithDevTools: ComposeWithDevTools =
+  typeof window !== 'undefined' &&
+  (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
+    ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
+    : function () {
+        if (arguments.length === 0) return undefined
+        if (typeof arguments[0] === 'object') return compose
+        return compose.apply(null, arguments as any as Function[])
+      }
+
+/**
+ * @public
+ */
+export const devToolsEnhancer: {
+  (options: DevToolsEnhancerOptions): StoreEnhancer<any>
+} =
+  typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__
+    ? (window as any).__REDUX_DEVTOOLS_EXTENSION__
+    : function () {
+        return function (noop) {
+          return noop
+        }
+      }
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,93 @@
+import type { Dispatch, Middleware, UnknownAction } from 'redux'
+import { compose } from '../reduxImports'
+import { createAction } from '../createAction'
+import { isAllOf } from '../matchers'
+import { nanoid } from '../nanoid'
+import { getOrInsertComputed } from '../utils'
+import type {
+  AddMiddleware,
+  DynamicMiddleware,
+  DynamicMiddlewareInstance,
+  MiddlewareEntry,
+  WithMiddleware,
+} from './types'
+export type {
+  DynamicMiddlewareInstance,
+  GetDispatchType as GetDispatch,
+  MiddlewareApiConfig,
+} from './types'
+
+const createMiddlewareEntry = <
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+>(
+  middleware: Middleware<any, State, DispatchType>,
+): MiddlewareEntry<State, DispatchType> => ({
+  middleware,
+  applied: new Map(),
+})
+
+const matchInstance =
+  (instanceId: string) =>
+  (action: any): action is { meta: { instanceId: string } } =>
+    action?.meta?.instanceId === instanceId
+
+export const createDynamicMiddleware = <
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+>(): DynamicMiddlewareInstance<State, DispatchType> => {
+  const instanceId = nanoid()
+  const middlewareMap = new Map<
+    Middleware<any, State, DispatchType>,
+    MiddlewareEntry<State, DispatchType>
+  >()
+
+  const withMiddleware = Object.assign(
+    createAction(
+      'dynamicMiddleware/add',
+      (...middlewares: Middleware<any, State, DispatchType>[]) => ({
+        payload: middlewares,
+        meta: {
+          instanceId,
+        },
+      }),
+    ),
+    { withTypes: () => withMiddleware },
+  ) as WithMiddleware<State, DispatchType>
+
+  const addMiddleware = Object.assign(
+    function addMiddleware(
+      ...middlewares: Middleware<any, State, DispatchType>[]
+    ) {
+      middlewares.forEach((middleware) => {
+        getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)
+      })
+    },
+    { withTypes: () => addMiddleware },
+  ) as AddMiddleware<State, DispatchType>
+
+  const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {
+    const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>
+      getOrInsertComputed(entry.applied, api, entry.middleware),
+    )
+    return compose(...appliedMiddleware)
+  }
+
+  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId))
+
+  const middleware: DynamicMiddleware<State, DispatchType> =
+    (api) => (next) => (action) => {
+      if (isWithMiddleware(action)) {
+        addMiddleware(...action.payload)
+        return api.dispatch
+      }
+      return getFinalMiddleware(api)(next)(action)
+    }
+
+  return {
+    middleware,
+    addMiddleware,
+    withMiddleware,
+    instanceId,
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,101 @@
+import type {
+  DynamicMiddlewareInstance,
+  GetDispatch,
+  GetState,
+  MiddlewareApiConfig,
+  TSHelpersExtractDispatchExtensions,
+} from '@reduxjs/toolkit'
+import { createDynamicMiddleware as cDM } from '@reduxjs/toolkit'
+import type { Context } from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import {
+  createDispatchHook,
+  ReactReduxContext,
+  useDispatch as useDefaultDispatch,
+} from 'react-redux'
+import type { Action, Dispatch, Middleware, UnknownAction } from 'redux'
+
+export type UseDispatchWithMiddlewareHook<
+  Middlewares extends Middleware<any, State, DispatchType>[] = [],
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType
+
+export type CreateDispatchWithMiddlewareHook<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  <
+    Middlewares extends [
+      Middleware<any, State, DispatchType>,
+      ...Middleware<any, State, DispatchType>[],
+    ],
+  >(
+    ...middlewares: Middlewares
+  ): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>
+  withTypes<
+    MiddlewareConfig extends MiddlewareApiConfig,
+  >(): CreateDispatchWithMiddlewareHook<
+    GetState<MiddlewareConfig>,
+    GetDispatch<MiddlewareConfig>
+  >
+}
+
+type ActionFromDispatch<DispatchType extends Dispatch<Action>> =
+  DispatchType extends Dispatch<infer Action> ? Action : never
+
+type ReactDynamicMiddlewareInstance<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = DynamicMiddlewareInstance<State, DispatchType> & {
+  createDispatchWithMiddlewareHookFactory: (
+    context?: Context<ReactReduxContextValue<
+      State,
+      ActionFromDispatch<DispatchType>
+    > | null>,
+  ) => CreateDispatchWithMiddlewareHook<State, DispatchType>
+  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<
+    State,
+    DispatchType
+  >
+}
+
+export const createDynamicMiddleware = <
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {
+  const instance = cDM<State, DispatchType>()
+  const createDispatchWithMiddlewareHookFactory = (
+    // @ts-ignore
+    context: Context<ReactReduxContextValue<
+      State,
+      ActionFromDispatch<DispatchType>
+    > | null> = ReactReduxContext,
+  ) => {
+    const useDispatch =
+      context === ReactReduxContext
+        ? useDefaultDispatch
+        : createDispatchHook(context)
+    function createDispatchWithMiddlewareHook<
+      Middlewares extends Middleware<any, State, DispatchType>[],
+    >(...middlewares: Middlewares) {
+      instance.addMiddleware(...middlewares)
+      return useDispatch
+    }
+    createDispatchWithMiddlewareHook.withTypes = () =>
+      createDispatchWithMiddlewareHook
+    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<
+      State,
+      DispatchType
+    >
+  }
+
+  const createDispatchWithMiddlewareHook =
+    createDispatchWithMiddlewareHookFactory()
+
+  return {
+    ...instance,
+    createDispatchWithMiddlewareHookFactory,
+    createDispatchWithMiddlewareHook,
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,95 @@
+import type { Action, Middleware, UnknownAction } from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import { configureStore } from '../../configureStore'
+import { createDynamicMiddleware } from '../index'
+
+const untypedInstance = createDynamicMiddleware()
+
+interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
+  (n: 1): 1
+}
+
+const typedInstance = createDynamicMiddleware<number, AppDispatch>()
+
+declare const staticMiddleware: Middleware<(n: 1) => 1>
+
+const store = configureStore({
+  reducer: () => 0,
+  middleware: (gDM) =>
+    gDM().prepend(typedInstance.middleware).concat(staticMiddleware),
+})
+
+declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
+declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
+
+declare const addedMiddleware: Middleware<(n: 2) => 2>
+
+describe('type tests', () => {
+  test('instance typed at creation ensures middleware compatibility with store', () => {
+    const store = configureStore({
+      reducer: () => '',
+      // @ts-expect-error
+      middleware: (gDM) => gDM().prepend(typedInstance.middleware),
+    })
+  })
+
+  test('instance typed at creation enforces correct middleware type', () => {
+    typedInstance.addMiddleware(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const dispatch = store.dispatch(
+      typedInstance.withMiddleware(
+        compatibleMiddleware,
+        // @ts-expect-error
+        incompatibleMiddleware,
+      ),
+    )
+  })
+
+  test('withTypes() enforces correct middleware type', () => {
+    const addMiddleware = untypedInstance.addMiddleware.withTypes<{
+      state: number
+      dispatch: AppDispatch
+    }>()
+
+    addMiddleware(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const withMiddleware = untypedInstance.withMiddleware.withTypes<{
+      state: number
+      dispatch: AppDispatch
+    }>()
+
+    const dispatch = store.dispatch(
+      withMiddleware(
+        compatibleMiddleware,
+        // @ts-expect-error
+        incompatibleMiddleware,
+      ),
+    )
+  })
+
+  test('withMiddleware returns typed dispatch, with any applicable extensions', () => {
+    const dispatch = store.dispatch(
+      typedInstance.withMiddleware(addedMiddleware),
+    )
+
+    // standard
+    expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
+
+    // thunk
+    expectTypeOf(dispatch(() => 'foo')).toBeString()
+
+    // static
+    expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
+
+    // added
+    expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/index.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,74 @@
+import type { Middleware } from 'redux'
+import { createDynamicMiddleware } from '../index'
+import { configureStore } from '../../configureStore'
+import type { BaseActionCreator, PayloadAction } from '../../createAction'
+import { createAction } from '../../createAction'
+import { isAllOf } from '../../matchers'
+
+const probeType = 'probeableMW/probe'
+
+export interface ProbeMiddleware
+  extends BaseActionCreator<number, typeof probeType> {
+  <Id extends number>(id: Id): PayloadAction<Id, typeof probeType>
+}
+
+export const probeMiddleware = createAction(probeType) as ProbeMiddleware
+
+const matchId =
+  <Id extends number>(id: Id) =>
+  (action: any): action is PayloadAction<Id> =>
+    action.payload === id
+
+export const makeProbeableMiddleware = <Id extends number>(
+  id: Id,
+): Middleware<{
+  (action: PayloadAction<Id, typeof probeType>): Id
+}> => {
+  const isMiddlewareAction = isAllOf(probeMiddleware, matchId(id))
+  return (api) => (next) => (action) => {
+    if (isMiddlewareAction(action)) {
+      return id
+    }
+    return next(action)
+  }
+}
+
+const staticMiddleware = makeProbeableMiddleware(1)
+
+describe('createDynamicMiddleware', () => {
+  it('allows injecting middleware after store instantiation', () => {
+    const dynamicInstance = createDynamicMiddleware()
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) =>
+        gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+    })
+    // normal, pre-inject
+    expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
+    // static
+    expect(store.dispatch(probeMiddleware(1))).toBe(1)
+
+    // inject
+    dynamicInstance.addMiddleware(makeProbeableMiddleware(2))
+
+    // injected
+    expect(store.dispatch(probeMiddleware(2))).toBe(2)
+  })
+  it('returns dispatch when withMiddleware is dispatched', () => {
+    const dynamicInstance = createDynamicMiddleware()
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend(dynamicInstance.middleware),
+    })
+
+    // normal, pre-inject
+    expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
+
+    const dispatch = store.dispatch(
+      dynamicInstance.withMiddleware(makeProbeableMiddleware(2)),
+    )
+    expect(dispatch).toEqual(expect.any(Function))
+
+    expect(dispatch(probeMiddleware(2))).toBe(2)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,81 @@
+import type { Context } from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import type { Action, Middleware, UnknownAction } from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import { createDynamicMiddleware } from '../react'
+
+interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
+  (n: 1): 1
+}
+
+const untypedInstance = createDynamicMiddleware()
+
+const typedInstance = createDynamicMiddleware<number, AppDispatch>()
+
+declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
+declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
+
+declare const customContext: Context<ReactReduxContextValue | null>
+
+declare const addedMiddleware: Middleware<(n: 2) => 2>
+
+describe('type tests', () => {
+  test('instance typed at creation enforces correct middleware type', () => {
+    const useDispatch = typedInstance.createDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const createDispatchWithMiddlewareHook =
+      typedInstance.createDispatchWithMiddlewareHookFactory(customContext)
+    const useDispatchWithContext = createDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+  })
+
+  test('withTypes() enforces correct middleware type', () => {
+    const createDispatchWithMiddlewareHook =
+      untypedInstance.createDispatchWithMiddlewareHook.withTypes<{
+        state: number
+        dispatch: AppDispatch
+      }>()
+    const useDispatch = createDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+
+    const createCustomDispatchWithMiddlewareHook = untypedInstance
+      .createDispatchWithMiddlewareHookFactory(customContext)
+      .withTypes<{
+        state: number
+        dispatch: AppDispatch
+      }>()
+    const useCustomDispatch = createCustomDispatchWithMiddlewareHook(
+      compatibleMiddleware,
+      // @ts-expect-error
+      incompatibleMiddleware,
+    )
+  })
+
+  test('useDispatchWithMW returns typed dispatch, with any applicable extensions', () => {
+    const useDispatchWithMW =
+      typedInstance.createDispatchWithMiddlewareHook(addedMiddleware)
+    const dispatch = useDispatchWithMW()
+
+    // standard
+    expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
+
+    // thunk
+    expectTypeOf(dispatch(() => 'foo')).toBeString()
+
+    // static
+    expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
+
+    // added
+    expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/tests/react.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,101 @@
+import * as React from 'react'
+import { createDynamicMiddleware } from '../react'
+import { configureStore } from '../../configureStore'
+import { makeProbeableMiddleware, probeMiddleware } from './index.test'
+import { render } from '@testing-library/react'
+import type { Dispatch } from 'redux'
+import type { ReactReduxContextValue } from 'react-redux'
+import { Provider } from 'react-redux'
+
+const staticMiddleware = makeProbeableMiddleware(1)
+
+describe('createReactDynamicMiddleware', () => {
+  describe('createDispatchWithMiddlewareHook', () => {
+    it('injects middleware upon creation', () => {
+      const dynamicInstance = createDynamicMiddleware()
+      const store = configureStore({
+        reducer: () => 0,
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+      // normal, pre-inject
+      expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))
+      // static
+      expect(store.dispatch(probeMiddleware(1))).toBe(1)
+
+      const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
+        makeProbeableMiddleware(2),
+      )
+
+      // injected
+      expect(store.dispatch(probeMiddleware(2))).toBe(2)
+    })
+
+    it('returns dispatch', () => {
+      const dynamicInstance = createDynamicMiddleware()
+      const store = configureStore({
+        reducer: () => 0,
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+
+      const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(
+        makeProbeableMiddleware(2),
+      )
+
+      let dispatch: Dispatch | undefined
+      function Component() {
+        dispatch = useDispatch()
+
+        return null
+      }
+      render(<Component />, {
+        wrapper: ({ children }) => (
+          <Provider store={store}>{children}</Provider>
+        ),
+      })
+      expect(dispatch).toBe(store.dispatch)
+    })
+  })
+  describe('createDispatchWithMiddlewareHookFactory', () => {
+    it('returns the correct store dispatch', () => {
+      const dynamicInstance = createDynamicMiddleware()
+      const store = configureStore({
+        reducer: () => 0,
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+      const store2 = configureStore({
+        reducer: () => '',
+        middleware: (gDM) =>
+          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),
+      })
+
+      const context = React.createContext<ReactReduxContextValue | null>(null)
+
+      const createDispatchWithMiddlewareHook =
+        dynamicInstance.createDispatchWithMiddlewareHookFactory(context)
+
+      const useDispatch = createDispatchWithMiddlewareHook(
+        makeProbeableMiddleware(2),
+      )
+
+      let dispatch: Dispatch | undefined
+      function Component() {
+        dispatch = useDispatch()
+
+        return null
+      }
+      render(<Component />, {
+        wrapper: ({ children }) => (
+          <Provider store={store}>
+            <Provider context={context} store={store2}>
+              {children}
+            </Provider>
+          </Provider>
+        ),
+      })
+      expect(dispatch).toBe(store2.dispatch)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,82 @@
+import type { Dispatch, Middleware, MiddlewareAPI, UnknownAction } from 'redux'
+import type { BaseActionCreator, PayloadAction } from '../createAction'
+import type { GetState } from '../createAsyncThunk'
+import type { ExtractDispatchExtensions, FallbackIfUnknown } from '../tsHelpers'
+
+export type GetMiddlewareApi<MiddlewareApiConfig> = MiddlewareAPI<
+  GetDispatchType<MiddlewareApiConfig>,
+  GetState<MiddlewareApiConfig>
+>
+
+export type MiddlewareApiConfig = {
+  state?: unknown
+  dispatch?: Dispatch
+}
+
+// TODO: consolidate with cAT helpers?
+export type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
+  dispatch: infer DispatchType
+}
+  ? FallbackIfUnknown<DispatchType, Dispatch>
+  : Dispatch
+
+export type AddMiddleware<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  (...middlewares: Middleware<any, State, DispatchType>[]): void
+  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<
+    GetState<MiddlewareConfig>,
+    GetDispatchType<MiddlewareConfig>
+  >
+}
+
+export type WithMiddleware<
+  State = any,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = BaseActionCreator<
+  Middleware<any, State, DispatchType>[],
+  'dynamicMiddleware/add',
+  { instanceId: string }
+> & {
+  <Middlewares extends Middleware<any, State, DispatchType>[]>(
+    ...middlewares: Middlewares
+  ): PayloadAction<Middlewares, 'dynamicMiddleware/add', { instanceId: string }>
+  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<
+    GetState<MiddlewareConfig>,
+    GetDispatchType<MiddlewareConfig>
+  >
+}
+
+export interface DynamicDispatch {
+  // return a version of dispatch that knows about middleware
+  <Middlewares extends Middleware<any>[]>(
+    action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>,
+  ): ExtractDispatchExtensions<Middlewares> & this
+}
+
+export type MiddlewareEntry<
+  State = unknown,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  middleware: Middleware<any, State, DispatchType>
+  applied: Map<
+    MiddlewareAPI<DispatchType, State>,
+    ReturnType<Middleware<any, State, DispatchType>>
+  >
+}
+
+export type DynamicMiddleware<
+  State = unknown,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = Middleware<DynamicDispatch, State, DispatchType>
+
+export type DynamicMiddlewareInstance<
+  State = unknown,
+  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
+> = {
+  middleware: DynamicMiddleware<State, DispatchType>
+  addMiddleware: AddMiddleware<State, DispatchType>
+  withMiddleware: WithMiddleware<State, DispatchType>
+  instanceId: string
+}
Index: node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,47 @@
+import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'
+import { createInitialStateFactory } from './entity_state'
+import { createSelectorsFactory } from './state_selectors'
+import { createSortedStateAdapter } from './sorted_state_adapter'
+import { createUnsortedStateAdapter } from './unsorted_state_adapter'
+import type { WithRequiredProp } from '../tsHelpers'
+
+export function createEntityAdapter<T, Id extends EntityId>(
+  options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,
+): EntityAdapter<T, Id>
+
+export function createEntityAdapter<T extends { id: EntityId }>(
+  options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,
+): EntityAdapter<T, T['id']>
+
+/**
+ *
+ * @param options
+ *
+ * @public
+ */
+export function createEntityAdapter<T>(
+  options: EntityAdapterOptions<T, EntityId> = {},
+): EntityAdapter<T, EntityId> {
+  const {
+    selectId,
+    sortComparer,
+  }: Required<EntityAdapterOptions<T, EntityId>> = {
+    sortComparer: false,
+    selectId: (instance: any) => instance.id,
+    ...options,
+  }
+
+  const stateAdapter = sortComparer
+    ? createSortedStateAdapter(selectId, sortComparer)
+    : createUnsortedStateAdapter(selectId)
+  const stateFactory = createInitialStateFactory(stateAdapter)
+  const selectorsFactory = createSelectorsFactory<T, EntityId>()
+
+  return {
+    selectId,
+    sortComparer,
+    ...stateFactory,
+    ...selectorsFactory,
+    ...stateAdapter,
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/entity_state.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/entity_state.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/entity_state.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,38 @@
+import type {
+  EntityId,
+  EntityState,
+  EntityStateAdapter,
+  EntityStateFactory,
+} from './models'
+
+export function getInitialEntityState<T, Id extends EntityId>(): EntityState<
+  T,
+  Id
+> {
+  return {
+    ids: [],
+    entities: {} as Record<Id, T>,
+  }
+}
+
+export function createInitialStateFactory<T, Id extends EntityId>(
+  stateAdapter: EntityStateAdapter<T, Id>,
+): EntityStateFactory<T, Id> {
+  function getInitialState(
+    state?: undefined,
+    entities?: readonly T[] | Record<Id, T>,
+  ): EntityState<T, Id>
+  function getInitialState<S extends object>(
+    additionalState: S,
+    entities?: readonly T[] | Record<Id, T>,
+  ): EntityState<T, Id> & S
+  function getInitialState(
+    additionalState: any = {},
+    entities?: readonly T[] | Record<Id, T>,
+  ): any {
+    const state = Object.assign(getInitialEntityState(), additionalState)
+    return entities ? stateAdapter.setAll(state, entities) : state
+  }
+
+  return { getInitialState }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+export { createEntityAdapter } from './create_adapter'
+export type {
+  EntityState,
+  EntityAdapter,
+  Update,
+  IdSelector,
+  Comparer,
+} from './models'
Index: node_modules/@reduxjs/toolkit/src/entities/models.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/models.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/models.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,198 @@
+import type { Draft } from 'immer'
+import type { PayloadAction } from '../createAction'
+import type { CastAny, Id } from '../tsHelpers'
+import type { UncheckedIndexedAccess } from '../uncheckedindexed.js'
+import type { GetSelectorsOptions } from './state_selectors'
+
+/**
+ * @public
+ */
+export type EntityId = number | string
+
+/**
+ * @public
+ */
+export type Comparer<T> = (a: T, b: T) => number
+
+/**
+ * @public
+ */
+export type IdSelector<T, Id extends EntityId> = (model: T) => Id
+
+/**
+ * @public
+ */
+export type Update<T, Id extends EntityId> = { id: Id; changes: Partial<T> }
+
+/**
+ * @public
+ */
+export interface EntityState<T, Id extends EntityId> {
+  ids: Id[]
+  entities: Record<Id, T>
+}
+
+/**
+ * @public
+ */
+export interface EntityAdapterOptions<T, Id extends EntityId> {
+  selectId?: IdSelector<T, Id>
+  sortComparer?: false | Comparer<T>
+}
+
+export type PreventAny<S, T, Id extends EntityId> = CastAny<
+  S,
+  EntityState<T, Id>
+>
+
+export type DraftableEntityState<T, Id extends EntityId> =
+  | EntityState<T, Id>
+  | Draft<EntityState<T, Id>>
+
+/**
+ * @public
+ */
+export interface EntityStateAdapter<T, Id extends EntityId> {
+  addOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: T,
+  ): S
+  addOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    action: PayloadAction<T>,
+  ): S
+
+  addMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  addMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+
+  setOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: T,
+  ): S
+  setOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    action: PayloadAction<T>,
+  ): S
+  setMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  setMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+  setAll<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  setAll<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+
+  removeOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    key: Id,
+  ): S
+  removeOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    key: PayloadAction<Id>,
+  ): S
+
+  removeMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    keys: readonly Id[],
+  ): S
+  removeMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    keys: PayloadAction<readonly Id[]>,
+  ): S
+
+  removeAll<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+  ): S
+
+  updateOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    update: Update<T, Id>,
+  ): S
+  updateOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    update: PayloadAction<Update<T, Id>>,
+  ): S
+
+  updateMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    updates: ReadonlyArray<Update<T, Id>>,
+  ): S
+  updateMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    updates: PayloadAction<ReadonlyArray<Update<T, Id>>>,
+  ): S
+
+  upsertOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: T,
+  ): S
+  upsertOne<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entity: PayloadAction<T>,
+  ): S
+
+  upsertMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: readonly T[] | Record<Id, T>,
+  ): S
+  upsertMany<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+    entities: PayloadAction<readonly T[] | Record<Id, T>>,
+  ): S
+}
+
+/**
+ * @public
+ */
+export interface EntitySelectors<T, V, IdType extends EntityId> {
+  selectIds: (state: V) => IdType[]
+  selectEntities: (state: V) => Record<IdType, T>
+  selectAll: (state: V) => T[]
+  selectTotal: (state: V) => number
+  selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>
+}
+
+/**
+ * @public
+ */
+export interface EntityStateFactory<T, Id extends EntityId> {
+  getInitialState(
+    state?: undefined,
+    entities?: Record<Id, T> | readonly T[],
+  ): EntityState<T, Id>
+  getInitialState<S extends object>(
+    state: S,
+    entities?: Record<Id, T> | readonly T[],
+  ): EntityState<T, Id> & S
+}
+
+/**
+ * @public
+ */
+export interface EntityAdapter<T, Id extends EntityId>
+  extends EntityStateAdapter<T, Id>,
+    EntityStateFactory<T, Id>,
+    Required<EntityAdapterOptions<T, Id>> {
+  getSelectors(
+    selectState?: undefined,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, EntityState<T, Id>, Id>
+  getSelectors<V>(
+    selectState: (state: V) => EntityState<T, Id>,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, V, Id>
+}
Index: node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,266 @@
+import type {
+  IdSelector,
+  Comparer,
+  EntityStateAdapter,
+  Update,
+  EntityId,
+  DraftableEntityState,
+} from './models'
+import { createStateOperator } from './state_adapter'
+import { createUnsortedStateAdapter } from './unsorted_state_adapter'
+import {
+  selectIdValue,
+  ensureEntitiesArray,
+  splitAddedUpdatedEntities,
+  getCurrent,
+} from './utils'
+
+// Borrowed from Replay
+export function findInsertIndex<T>(
+  sortedItems: T[],
+  item: T,
+  comparisonFunction: Comparer<T>,
+): number {
+  let lowIndex = 0
+  let highIndex = sortedItems.length
+  while (lowIndex < highIndex) {
+    let middleIndex = (lowIndex + highIndex) >>> 1
+    const currentItem = sortedItems[middleIndex]
+    const res = comparisonFunction(item, currentItem)
+    if (res >= 0) {
+      lowIndex = middleIndex + 1
+    } else {
+      highIndex = middleIndex
+    }
+  }
+
+  return lowIndex
+}
+
+export function insert<T>(
+  sortedItems: T[],
+  item: T,
+  comparisonFunction: Comparer<T>,
+): T[] {
+  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction)
+
+  sortedItems.splice(insertAtIndex, 0, item)
+
+  return sortedItems
+}
+
+export function createSortedStateAdapter<T, Id extends EntityId>(
+  selectId: IdSelector<T, Id>,
+  comparer: Comparer<T>,
+): EntityStateAdapter<T, Id> {
+  type R = DraftableEntityState<T, Id>
+
+  const { removeOne, removeMany, removeAll } =
+    createUnsortedStateAdapter(selectId)
+
+  function addOneMutably(entity: T, state: R): void {
+    return addManyMutably([entity], state)
+  }
+
+  function addManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+    existingIds?: Id[],
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+
+    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids))
+    const addedKeys = new Set<Id>();
+    const models = newEntities.filter(
+      (model) => {
+          const modelId = selectIdValue(model, selectId);
+          const notAdded = !addedKeys.has(modelId);
+          if (notAdded) addedKeys.add(modelId);
+          return !existingKeys.has(modelId) && notAdded;
+      }
+    )
+
+    if (models.length !== 0) {
+      mergeFunction(state, models)
+    }
+  }
+
+  function setOneMutably(entity: T, state: R): void {
+    return setManyMutably([entity], state)
+  }
+
+  function setManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    let deduplicatedEntities = {} as Record<Id, T>;
+    newEntities = ensureEntitiesArray(newEntities)
+    if (newEntities.length !== 0) {
+      for (const item of newEntities) {
+        const entityId = selectId(item);
+        // For multiple items with the same ID, we should keep the last one.
+        deduplicatedEntities[entityId] = item;
+        delete (state.entities as Record<Id, T>)[entityId]
+      }
+      newEntities = ensureEntitiesArray(deduplicatedEntities);
+      mergeFunction(state, newEntities)
+    }
+  }
+
+  function setAllMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+    state.entities = {} as Record<Id, T>
+    state.ids = []
+
+    addManyMutably(newEntities, state, [])
+  }
+
+  function updateOneMutably(update: Update<T, Id>, state: R): void {
+    return updateManyMutably([update], state)
+  }
+
+  function updateManyMutably(
+    updates: ReadonlyArray<Update<T, Id>>,
+    state: R,
+  ): void {
+    let appliedUpdates = false
+    let replacedIds = false
+
+    for (let update of updates) {
+      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id]
+      if (!entity) {
+        continue
+      }
+
+      appliedUpdates = true
+
+      Object.assign(entity, update.changes)
+      const newId = selectId(entity)
+
+      if (update.id !== newId) {
+        // We do support the case where updates can change an item's ID.
+        // This makes things trickier - go ahead and swap the IDs in state now.
+        replacedIds = true
+        delete (state.entities as Record<Id, T>)[update.id]
+        const oldIndex = (state.ids as Id[]).indexOf(update.id)
+        state.ids[oldIndex] = newId
+        ;(state.entities as Record<Id, T>)[newId] = entity
+      }
+    }
+
+    if (appliedUpdates) {
+      mergeFunction(state, [], appliedUpdates, replacedIds)
+    }
+  }
+
+  function upsertOneMutably(entity: T, state: R): void {
+    return upsertManyMutably([entity], state)
+  }
+
+  function upsertManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(
+      newEntities,
+      selectId,
+      state,
+    )
+
+    if (added.length) {
+      addManyMutably(added, state, existingIdsArray)
+    }
+    if (updated.length) {
+      updateManyMutably(updated, state)
+    }
+  }
+
+  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {
+    if (a.length !== b.length) {
+      return false
+    }
+
+    for (let i = 0; i < a.length; i++) {
+      if (a[i] === b[i]) {
+        continue
+      }
+      return false
+    }
+    return true
+  }
+
+  type MergeFunction = (
+    state: R,
+    addedItems: readonly T[],
+    appliedUpdates?: boolean,
+    replacedIds?: boolean,
+  ) => void
+
+  const mergeFunction: MergeFunction = (
+    state,
+    addedItems,
+    appliedUpdates,
+    replacedIds,
+  ) => {
+    const currentEntities = getCurrent(state.entities)
+    const currentIds = getCurrent(state.ids)
+
+    const stateEntities = state.entities as Record<Id, T>
+
+    let ids: Iterable<Id> = currentIds
+    if (replacedIds) {
+      ids = new Set(currentIds)
+    }
+
+    let sortedEntities: T[] = []
+    for (const id of ids) {
+      const entity = currentEntities[id]
+      if (entity) {
+        sortedEntities.push(entity)
+      }
+    }
+    const wasPreviouslyEmpty = sortedEntities.length === 0
+
+    // Insert/overwrite all new/updated
+    for (const item of addedItems) {
+      stateEntities[selectId(item)] = item
+
+      if (!wasPreviouslyEmpty) {
+        // Binary search insertion generally requires fewer comparisons
+        insert(sortedEntities, item, comparer)
+      }
+    }
+
+    if (wasPreviouslyEmpty) {
+      // All we have is the incoming values, sort them
+      sortedEntities = addedItems.slice().sort(comparer)
+    } else if (appliedUpdates) {
+      // We should have a _mostly_-sorted array already
+      sortedEntities.sort(comparer)
+    }
+
+    const newSortedIds = sortedEntities.map(selectId)
+
+    if (!areArraysEqual(currentIds, newSortedIds)) {
+      state.ids = newSortedIds
+    }
+  }
+
+  return {
+    removeOne,
+    removeMany,
+    removeAll,
+    addOne: createStateOperator(addOneMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    addMany: createStateOperator(addManyMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,58 @@
+import { createNextState, isDraft } from '../immerImports'
+import type { Draft } from 'immer'
+import type { EntityId, DraftableEntityState, PreventAny } from './models'
+import type { PayloadAction } from '../createAction'
+import { isFSA } from '../createAction'
+
+export const isDraftTyped = isDraft as <T>(
+  value: T | Draft<T>,
+) => value is Draft<T>
+
+export function createSingleArgumentStateOperator<T, Id extends EntityId>(
+  mutator: (state: DraftableEntityState<T, Id>) => void,
+) {
+  const operator = createStateOperator(
+    (_: undefined, state: DraftableEntityState<T, Id>) => mutator(state),
+  )
+
+  return function operation<S extends DraftableEntityState<T, Id>>(
+    state: PreventAny<S, T, Id>,
+  ): S {
+    return operator(state as S, undefined)
+  }
+}
+
+export function createStateOperator<T, Id extends EntityId, R>(
+  mutator: (arg: R, state: DraftableEntityState<T, Id>) => void,
+) {
+  return function operation<S extends DraftableEntityState<T, Id>>(
+    state: S,
+    arg: R | PayloadAction<R>,
+  ): S {
+    function isPayloadActionArgument(
+      arg: R | PayloadAction<R>,
+    ): arg is PayloadAction<R> {
+      return isFSA(arg)
+    }
+
+    const runMutator = (draft: DraftableEntityState<T, Id>) => {
+      if (isPayloadActionArgument(arg)) {
+        mutator(arg.payload, draft)
+      } else {
+        mutator(arg, draft)
+      }
+    }
+
+    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {
+      // we must already be inside a `createNextState` call, likely because
+      // this is being wrapped in `createReducer` or `createSlice`.
+      // It's safe to just pass the draft to the mutator.
+      runMutator(state)
+
+      // since it's a draft, we'll just return it
+      return state
+    }
+
+    return createNextState(state, runMutator)
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,73 @@
+import type { CreateSelectorFunction, Selector } from 'reselect'
+import { createDraftSafeSelector } from '../createDraftSafeSelector'
+import type { EntityId, EntitySelectors, EntityState } from './models'
+
+type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>
+
+export type GetSelectorsOptions = {
+  createSelector?: AnyCreateSelectorFunction
+}
+
+export function createSelectorsFactory<T, Id extends EntityId>() {
+  function getSelectors(
+    selectState?: undefined,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, EntityState<T, Id>, Id>
+  function getSelectors<V>(
+    selectState: (state: V) => EntityState<T, Id>,
+    options?: GetSelectorsOptions,
+  ): EntitySelectors<T, V, Id>
+  function getSelectors<V>(
+    selectState?: (state: V) => EntityState<T, Id>,
+    options: GetSelectorsOptions = {},
+  ): EntitySelectors<T, any, Id> {
+    const {
+      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,
+    } = options
+
+    const selectIds = (state: EntityState<T, Id>) => state.ids
+
+    const selectEntities = (state: EntityState<T, Id>) => state.entities
+
+    const selectAll = createSelector(
+      selectIds,
+      selectEntities,
+      (ids, entities): T[] => ids.map((id) => entities[id]!),
+    )
+
+    const selectId = (_: unknown, id: Id) => id
+
+    const selectById = (entities: Record<Id, T>, id: Id) => entities[id]
+
+    const selectTotal = createSelector(selectIds, (ids) => ids.length)
+
+    if (!selectState) {
+      return {
+        selectIds,
+        selectEntities,
+        selectAll,
+        selectTotal,
+        selectById: createSelector(selectEntities, selectId, selectById),
+      }
+    }
+
+    const selectGlobalizedEntities = createSelector(
+      selectState as Selector<V, EntityState<T, Id>>,
+      selectEntities,
+    )
+
+    return {
+      selectIds: createSelector(selectState, selectIds),
+      selectEntities: selectGlobalizedEntities,
+      selectAll: createSelector(selectState, selectAll),
+      selectTotal: createSelector(selectState, selectTotal),
+      selectById: createSelector(
+        selectGlobalizedEntities,
+        selectId,
+        selectById,
+      ),
+    }
+  }
+
+  return { getSelectors }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/tests/entity_slice_enhancer.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/entity_slice_enhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/entity_slice_enhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,59 @@
+import { createEntityAdapter, createSlice } from '../..'
+import type {
+  PayloadAction,
+  Slice,
+  SliceCaseReducers,
+  UnknownAction,
+} from '../..'
+import type { EntityId, EntityState, IdSelector } from '../models'
+import type { BookModel } from './fixtures/book'
+
+describe('Entity Slice Enhancer', () => {
+  let slice: Slice<EntityState<BookModel, BookModel['id']>>
+
+  beforeEach(() => {
+    const indieSlice = entitySliceEnhancer({
+      name: 'book',
+      selectId: (book: BookModel) => book.id,
+    })
+    slice = indieSlice
+  })
+
+  it('exposes oneAdded', () => {
+    const book = {
+      id: '0',
+      title: 'Der Steppenwolf',
+      author: 'Herman Hesse',
+    }
+    const action = slice.actions.oneAdded(book)
+    const oneAdded = slice.reducer(undefined, action as UnknownAction)
+    expect(oneAdded.entities['0']).toBe(book)
+  })
+})
+
+interface EntitySliceArgs<T, Id extends EntityId> {
+  name: string
+  selectId: IdSelector<T, Id>
+  modelReducer?: SliceCaseReducers<T>
+}
+
+function entitySliceEnhancer<T, Id extends EntityId>({
+  name,
+  selectId,
+  modelReducer,
+}: EntitySliceArgs<T, Id>) {
+  const modelAdapter = createEntityAdapter({
+    selectId,
+  })
+
+  return createSlice({
+    name,
+    initialState: modelAdapter.getInitialState(),
+    reducers: {
+      oneAdded(state, action: PayloadAction<T>) {
+        modelAdapter.addOne(state, action.payload)
+      },
+      ...modelReducer,
+    },
+  })
+}
Index: node_modules/@reduxjs/toolkit/src/entities/tests/entity_state.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/entity_state.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/entity_state.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,104 @@
+import type { EntityAdapter } from '../index'
+import { createEntityAdapter } from '../index'
+import type { PayloadAction } from '../../createAction'
+import { createAction } from '../../createAction'
+import { createSlice } from '../../createSlice'
+import type { BookModel } from './fixtures/book'
+
+describe('Entity State', () => {
+  let adapter: EntityAdapter<BookModel, string>
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+    })
+  })
+
+  it('should let you get the initial state', () => {
+    const initialState = adapter.getInitialState()
+
+    expect(initialState).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you provide additional initial state properties', () => {
+    const additionalProperties = { isHydrated: true }
+
+    const initialState = adapter.getInitialState(additionalProperties)
+
+    expect(initialState).toEqual({
+      ...additionalProperties,
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you provide initial entities', () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+
+    const initialState = adapter.getInitialState(undefined, [book1])
+
+    expect(initialState).toEqual({
+      ids: [book1.id],
+      entities: { [book1.id]: book1 },
+    })
+
+    const additionalProperties = { isHydrated: true }
+
+    const initialState2 = adapter.getInitialState(additionalProperties, [book1])
+
+    expect(initialState2).toEqual({
+      ...additionalProperties,
+      ids: [book1.id],
+      entities: { [book1.id]: book1 },
+    })
+  })
+
+  it('should allow methods to be passed as reducers', () => {
+    const upsertBook = createAction<BookModel>('otherBooks/upsert')
+
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        addOne: adapter.addOne,
+        removeOne(state, action: PayloadAction<string>) {
+          // TODO The nested `produce` calls don't mutate `state` here as I would have expected.
+          // TODO (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
+          // TODO However, this works if we _return_ the new plain result value instead
+          // TODO See https://github.com/immerjs/immer/issues/533
+          const result = adapter.removeOne(state, action)
+          return result
+        },
+      },
+      extraReducers: (builder) => {
+        builder.addCase(upsertBook, (state, action) => {
+          return adapter.upsertOne(state, action)
+        })
+      },
+    })
+
+    const { addOne, removeOne } = booksSlice.actions
+    const { reducer } = booksSlice
+
+    const selectors = adapter.getSelectors()
+
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book1a: BookModel = { id: 'a', title: 'Second' }
+
+    const afterAddOne = reducer(undefined, addOne(book1))
+    expect(afterAddOne.entities[book1.id]).toBe(book1)
+
+    const afterRemoveOne = reducer(afterAddOne, removeOne(book1.id))
+    expect(afterRemoveOne.entities[book1.id]).toBeUndefined()
+    expect(selectors.selectTotal(afterRemoveOne)).toBe(0)
+
+    const afterUpsertFirst = reducer(afterRemoveOne, upsertBook(book1))
+    const afterUpsertSecond = reducer(afterUpsertFirst, upsertBook(book1a))
+
+    expect(afterUpsertSecond.entities[book1.id]).toEqual(book1a)
+    expect(selectors.selectTotal(afterUpsertSecond)).toBe(1)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/fixtures/book.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/fixtures/book.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/fixtures/book.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,26 @@
+export interface BookModel {
+  id: string
+  title: string
+  author?: string
+}
+
+export const AClockworkOrange: BookModel = Object.freeze({
+  id: 'aco',
+  title: 'A Clockwork Orange',
+})
+
+export const AnimalFarm: BookModel = Object.freeze({
+  id: 'af',
+  title: 'Animal Farm',
+})
+
+export const TheGreatGatsby: BookModel = Object.freeze({
+  id: 'tgg',
+  title: 'The Great Gatsby',
+})
+
+export const TheHobbit: BookModel = Object.freeze({
+  id: 'th',
+  title: 'The Hobbit',
+  author: 'J. R. R. Tolkien',
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/sorted_state_adapter.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/sorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/sorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1181 @@
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAction,
+  createSlice,
+  nanoid,
+} from '@reduxjs/toolkit'
+import { createNextState } from '../..'
+import { createEntityAdapter } from '../create_adapter'
+import type { EntityAdapter, EntityState } from '../models'
+import type { BookModel } from './fixtures/book'
+import {
+  AClockworkOrange,
+  AnimalFarm,
+  TheGreatGatsby,
+  TheHobbit,
+} from './fixtures/book'
+
+describe('Sorted State Adapter', () => {
+  let adapter: EntityAdapter<BookModel, string>
+  let state: EntityState<BookModel, string>
+
+  beforeAll(() => {
+    //eslint-disable-next-line
+    Object.defineProperty(Array.prototype, 'unwantedField', {
+      enumerable: true,
+      configurable: true,
+      value: 'This should not appear anywhere',
+    })
+  })
+
+  afterAll(() => {
+    delete (Array.prototype as any).unwantedField
+  })
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+      sortComparer: (a, b) => {
+        return a.title.localeCompare(b.title)
+      },
+    })
+
+    state = { ids: [], entities: {} }
+  })
+
+  it('should let you add one entity to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you add one entity to the state as an FSA', () => {
+    const bookAction = createAction<BookModel>('books/add')
+    const withOneEntity = adapter.addOne(state, bookAction(TheGreatGatsby))
+
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should not change state if you attempt to re-add an entity', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const readded = adapter.addOne(withOneEntity, TheGreatGatsby)
+
+    expect(readded).toBe(withOneEntity)
+  })
+
+  it('should let you add many entities to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withManyMore).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add many entities to the state from a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withManyMore).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll when passing in a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on addAll (deprecated)', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add remove an entity from the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)
+
+    expect(withoutOne).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you remove many entities by id from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutMany = adapter.removeMany(withAll, [
+      TheGreatGatsby.id,
+      AClockworkOrange.id,
+    ])
+
+    expect(withoutMany).toEqual({
+      ids: [AnimalFarm.id],
+      entities: {
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you remove all entities from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutAll = adapter.removeAll(withAll)
+
+    expect(withoutAll).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you update an entity in the state', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should not change state if you attempt to update an entity that has not been added', () => {
+    const withUpdates = adapter.updateOne(state, {
+      id: TheGreatGatsby.id,
+      changes: { title: 'A New Title' },
+    })
+
+    expect(withUpdates).toBe(state)
+  })
+
+  it('Replaces an existing entity if you change the ID while updating', () => {
+    const a = { id: 'a', title: 'First' }
+    const b = { id: 'b', title: 'Second' }
+    const c = { id: 'c', title: 'Third' }
+    const d = { id: 'd', title: 'Fourth' }
+    const withAdded = adapter.setAll(state, [a, b, c])
+
+    const withUpdated = adapter.updateOne(withAdded, {
+      id: 'b',
+      changes: {
+        id: 'c',
+      },
+    })
+
+    const { ids, entities } = withUpdated
+
+    expect(ids).toEqual(['a', 'c'])
+    expect(entities.a).toBeTruthy()
+    expect(entities.b).not.toBeTruthy()
+    expect(entities.c).toBeTruthy()
+    expect(entities.c!.id).toBe('c')
+    expect(entities.c!.title).toBe('Second')
+  })
+
+  it('should not change ids state if you attempt to update an entity that does not impact sorting', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+    const changes = { title: 'The Great Gatsby II' }
+
+    const withUpdates = adapter.updateOne(withAll, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withAll.ids).toBe(withUpdates.ids)
+  })
+
+  it('should let you update the id of entity', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { id: 'A New Id' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [changes.id],
+      entities: {
+        [changes.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should resort correctly if same id but sort key update', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AnimalFarm,
+      AClockworkOrange,
+    ])
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withAll, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should resort correctly if the id and sort key update', () => {
+    const withOne = adapter.setAll(state, [
+      TheGreatGatsby,
+      AnimalFarm,
+      AClockworkOrange,
+    ])
+    const changes = { id: 'A New Id', title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [AClockworkOrange.id, changes.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [changes.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should maintain a stable sorting order when updating items', () => {
+    interface OrderedEntity {
+      id: string
+      order: number
+      ts: number
+    }
+    const sortedItemsAdapter = createEntityAdapter<OrderedEntity>({
+      sortComparer: (a, b) => a.order - b.order,
+    })
+    const withInitialItems = sortedItemsAdapter.setAll(
+      sortedItemsAdapter.getInitialState(),
+      [
+        { id: 'C', order: 3, ts: 0 },
+        { id: 'A', order: 1, ts: 0 },
+        { id: 'F', order: 4, ts: 0 },
+        { id: 'B', order: 2, ts: 0 },
+        { id: 'D', order: 3, ts: 0 },
+        { id: 'E', order: 3, ts: 0 },
+      ],
+    )
+
+    expect(withInitialItems.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
+
+    const updated = sortedItemsAdapter.updateOne(withInitialItems, {
+      id: 'C',
+      changes: { ts: 5 },
+    })
+
+    expect(updated.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
+
+    const updated2 = sortedItemsAdapter.updateOne(withInitialItems, {
+      id: 'D',
+      changes: { ts: 6 },
+    })
+
+    expect(updated2.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
+  })
+
+  it('should let you update many entities by id in the state', () => {
+    const firstChange = { title: 'Zack' }
+    const secondChange = { title: 'Aaron' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])
+
+    const withUpdates = adapter.updateMany(withMany, [
+      { id: TheGreatGatsby.id, changes: firstChange },
+      { id: AClockworkOrange.id, changes: secondChange },
+    ])
+
+    expect(withUpdates).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...secondChange,
+        },
+      },
+    })
+  })
+
+  it('should let you add one entity to the state with upsert()', () => {
+    const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you update an entity in the state with upsert()', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.upsertOne(withOne, {
+      ...TheGreatGatsby,
+      ...changes,
+    })
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should let you upsert many entities in the state', () => {
+    const firstChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      { ...TheGreatGatsby, ...firstChange },
+      AClockworkOrange,
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should do nothing when upsertMany is given an empty array', () => {
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should throw when upsertMany is passed undefined or null', async () => {
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const fakeRequest = (response: null | undefined) =>
+      new Promise((resolve) => setTimeout(() => resolve(response), 50))
+
+    const undefinedBooks = (await fakeRequest(undefined)) as BookModel[]
+    expect(() => adapter.upsertMany(withMany, undefinedBooks)).toThrow()
+
+    const nullBooks = (await fakeRequest(null)) as BookModel[]
+    expect(() => adapter.upsertMany(withMany, nullBooks)).toThrow()
+  })
+
+  it('should let you upsert many entities in the state when passing in a dictionary', () => {
+    const firstChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, {
+      [TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withUpserts).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you add a new entity then apply changes to it', () => {
+    const firstChange = { author: TheHobbit.author }
+    const secondChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [AClockworkOrange])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      {...TheGreatGatsby}, { ...TheGreatGatsby, ...firstChange }, {...TheGreatGatsby, ...secondChange}
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [AClockworkOrange.id, TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+          ...secondChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you add a new entity in the state with setOne() and keep the sorting', () => {
+    const withMany = adapter.setAll(state, [AnimalFarm, TheHobbit])
+    const withOneMore = adapter.setOne(withMany, TheGreatGatsby)
+    expect(withOneMore).toEqual({
+      ids: [AnimalFarm.id, TheGreatGatsby.id, TheHobbit.id],
+      entities: {
+        [AnimalFarm.id]: AnimalFarm,
+        [TheHobbit.id]: TheHobbit,
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you replace an entity in the state with setOne()', () => {
+    let withOne = adapter.setOne(state, TheHobbit)
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    withOne = adapter.setOne(withOne, changeWithoutAuthor)
+
+    expect(withOne).toEqual({
+      ids: [TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+      },
+    })
+  })
+
+  it('should do nothing when setMany is given an empty array', () => {
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.setMany(withMany, [])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you set many entities in the state', () => {
+    const firstChange = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, [
+      firstChange,
+      AClockworkOrange,
+    ])
+
+    expect(withSetMany).toEqual({
+      ids: [AClockworkOrange.id, TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: firstChange,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {
+    const unsortedAdaptor = createEntityAdapter({
+      selectId: (book: BookModel) => book.id
+    });
+
+    const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
+    const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
+    const withNothingSorted = adapter.setAll(state, []);
+    const withNothingUnsorted = unsortedAdaptor.setAll(state, []);
+    const withOneSorted = adapter.addMany(withNothingSorted, [
+      { ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
+    ])
+    const withOneUnsorted = adapter.addMany(withNothingUnsorted, [
+      { ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
+    ])
+
+    expect(withOneSorted).toEqual(withOneUnsorted);
+  })
+
+  it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {
+    const unsortedAdaptor = createEntityAdapter({
+      selectId: (book: BookModel) => book.id
+    });
+
+    const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
+    const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
+    const withNothingSorted = adapter.setAll(state, [TheHobbit]);
+    const withNothingUnsorted = unsortedAdaptor.setAll(state, [TheHobbit]);
+    const withOneSorted = adapter.setMany(withNothingSorted, [
+      { ...AClockworkOrange, ...firstEntry, id: 'th' }, {...AClockworkOrange, ...secondEntry, id: 'th'}
+    ])
+    const withOneUnsorted = unsortedAdaptor.setMany(withNothingUnsorted, [
+      { ...AClockworkOrange, ...firstEntry, id: 'th' }, {...AClockworkOrange, ...secondEntry, id: 'th'}
+    ])
+
+    expect(withOneSorted).toEqual(withOneUnsorted);
+  })
+
+  it('should let you set many entities in the state when passing in a dictionary', () => {
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, {
+      [TheHobbit.id]: changeWithoutAuthor,
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withSetMany).toEqual({
+      ids: [AClockworkOrange.id, TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it("only returns one entry for that id in the id's array", () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    const initialState = adapter.getInitialState()
+    const withItems = adapter.addMany(initialState, [book1, book2])
+
+    expect(withItems.ids).toEqual(['a', 'b'])
+    const withUpdate = adapter.updateOne(withItems, {
+      id: 'a',
+      changes: { id: 'b' },
+    })
+
+    expect(withUpdate.ids).toEqual(['b'])
+    expect(withUpdate.entities['b']!.title).toBe(book1.title)
+  })
+
+  it('should minimize the amount of sorting work needed', () => {
+    const INITIAL_ITEMS = 10_000
+    const ADDED_ITEMS = 1_000
+
+    type Entity = { id: string; name: string; position: number }
+
+    let numSorts = 0
+
+    const adaptor = createEntityAdapter({
+      selectId: (entity: Entity) => entity.id,
+      sortComparer: (a, b) => {
+        numSorts++
+        if (a.position < b.position) return -1
+        else if (a.position > b.position) return 1
+        return 0
+      },
+    })
+
+    function generateItems(count: number) {
+      const items: readonly Entity[] = new Array(count)
+        .fill(undefined)
+        .map((x, i) => ({
+          name: `${i}`,
+          position: Math.random(),
+          id: nanoid(),
+        }))
+      return items
+    }
+
+    const entitySlice = createSlice({
+      name: 'entity',
+      initialState: adaptor.getInitialState(),
+      reducers: {
+        updateOne: adaptor.updateOne,
+        upsertOne: adaptor.upsertOne,
+        upsertMany: adaptor.upsertMany,
+        addMany: adaptor.addMany,
+      },
+    })
+
+    const store = configureStore({
+      reducer: {
+        entity: entitySlice.reducer,
+      },
+      middleware: (getDefaultMiddleware) => {
+        return getDefaultMiddleware({
+          serializableCheck: false,
+          immutableCheck: false,
+        })
+      },
+    })
+
+    numSorts = 0
+
+    const logComparisons = false
+
+    function measureComparisons(name: string, cb: () => void) {
+      numSorts = 0
+      const start = new Date().getTime()
+      cb()
+      const end = new Date().getTime()
+      const duration = end - start
+
+      if (logComparisons) {
+        console.log(
+          `${name}: sortComparer called ${numSorts.toLocaleString()} times in ${duration.toLocaleString()}ms`,
+        )
+      }
+    }
+
+    const initialItems = generateItems(INITIAL_ITEMS)
+
+    measureComparisons('Original Setup', () => {
+      store.dispatch(entitySlice.actions.upsertMany(initialItems))
+    })
+
+    expect(numSorts).toBeLessThan(INITIAL_ITEMS * 20)
+
+    measureComparisons('Insert One (random)', () => {
+      store.dispatch(
+        entitySlice.actions.upsertOne({
+          id: nanoid(),
+          position: Math.random(),
+          name: 'test',
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(50)
+
+    measureComparisons('Insert One (middle)', () => {
+      store.dispatch(
+        entitySlice.actions.upsertOne({
+          id: nanoid(),
+          position: 0.5,
+          name: 'test',
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(50)
+
+    measureComparisons('Insert One (end)', () => {
+      store.dispatch(
+        entitySlice.actions.upsertOne({
+          id: nanoid(),
+          position: 0.9998,
+          name: 'test',
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(50)
+
+    const addedItems = generateItems(ADDED_ITEMS)
+    measureComparisons('Add Many', () => {
+      store.dispatch(entitySlice.actions.addMany(addedItems))
+    })
+
+    expect(numSorts).toBeLessThan(ADDED_ITEMS * 20)
+
+    // These numbers will vary because of the randomness, but generally
+    // with 10K items the old code had 200K+ sort calls, while the new code
+    // is around 13K sort calls.
+    expect(numSorts).toBeLessThan(20_000)
+
+    const { ids } = store.getState().entity
+    const middleItemId = ids[(ids.length / 2) | 0]
+
+    measureComparisons('Update One (end)', () => {
+      store.dispatch(
+        // Move this middle item near the end
+        entitySlice.actions.updateOne({
+          id: middleItemId,
+          changes: {
+            position: 0.99999,
+          },
+        }),
+      )
+    })
+
+    const SORTING_COUNT_BUFFER = 100
+
+    expect(numSorts).toBeLessThan(
+      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,
+    )
+
+    measureComparisons('Update One (middle)', () => {
+      store.dispatch(
+        // Move this middle item near the end
+        entitySlice.actions.updateOne({
+          id: middleItemId,
+          changes: {
+            position: 0.42,
+          },
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(
+      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,
+    )
+
+    measureComparisons('Update One (replace)', () => {
+      store.dispatch(
+        // Move this middle item near the end
+        entitySlice.actions.updateOne({
+          id: middleItemId,
+          changes: {
+            id: nanoid(),
+            position: 0.98,
+          },
+        }),
+      )
+    })
+
+    expect(numSorts).toBeLessThan(
+      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,
+    )
+
+    // The old code was around 120K, the new code is around 10K.
+    //expect(numSorts).toBeLessThan(25_000)
+  })
+
+  it('should not throw an Immer `current` error when `state.ids` is a plain array', () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const initialState = adapter.getInitialState()
+    const withItems = adapter.addMany(initialState, [book1])
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState,
+      reducers: {
+        testCurrentBehavior(state, action: PayloadAction<BookModel>) {
+          // Will overwrite `state.ids` with a plain array
+          adapter.removeAll(state)
+
+          // will call `splitAddedUpdatedEntities` and call `current(state.ids)`
+          adapter.upsertMany(state, [book1])
+        },
+      },
+    })
+
+    booksSlice.reducer(
+      initialState,
+      booksSlice.actions.testCurrentBehavior(book1),
+    )
+  })
+
+  it('should not throw an Immer `current` error when the adapter is called twice', () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    const initialState = adapter.getInitialState()
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState,
+      reducers: {
+        testCurrentBehavior(state, action: PayloadAction<BookModel>) {
+          // Will overwrite `state.ids` with a plain array
+          adapter.removeAll(state)
+
+          // will call `splitAddedUpdatedEntities` and call `current(state.ids)`
+          adapter.addOne(state, book1)
+          adapter.addOne(state, book2)
+        },
+      },
+    })
+
+    booksSlice.reducer(
+      initialState,
+      booksSlice.actions.testCurrentBehavior(book1),
+    )
+  })
+
+  describe('can be used mutably when wrapped in createNextState', () => {
+    test('removeAll', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeAll(draft)
+      })
+      expect(result).toEqual({
+        entities: {},
+        ids: [],
+      })
+    })
+
+    test('addOne', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addOne(draft, TheGreatGatsby)
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('addMany', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['af', 'tgg'],
+      })
+    })
+
+    test('setAll', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['af', 'tgg'],
+      })
+    })
+
+    test('updateOne', () => {
+      const withOne = adapter.addOne(state, TheGreatGatsby)
+      const changes = { title: 'A New Hope' }
+      const result = createNextState(withOne, (draft) => {
+        adapter.updateOne(draft, {
+          id: TheGreatGatsby.id,
+          changes,
+        })
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('updateMany', () => {
+      const firstChange = { title: 'First Change' }
+      const secondChange = { title: 'Second Change' }
+      const thirdChange = { title: 'Third Change' }
+      const fourthChange = { author: 'Fourth Change' }
+      const withMany = adapter.setAll(state, [
+        TheGreatGatsby,
+        AClockworkOrange,
+        TheHobbit,
+      ])
+
+      const result = createNextState(withMany, (draft) => {
+        adapter.updateMany(draft, [
+          { id: TheHobbit.id, changes: firstChange },
+          { id: TheGreatGatsby.id, changes: secondChange },
+          { id: AClockworkOrange.id, changes: thirdChange },
+          { id: TheHobbit.id, changes: fourthChange },
+        ])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'Third Change',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'Second Change',
+          },
+          th: {
+            author: 'Fourth Change',
+            id: 'th',
+            title: 'First Change',
+          },
+        },
+        ids: ['th', 'tgg', 'aco'],
+      })
+    })
+
+    test('upsertOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.upsertOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertOne (update)', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertOne(draft, {
+          id: TheGreatGatsby.id,
+          title: 'A New Hope',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertMany', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertMany(draft, [
+          {
+            id: TheGreatGatsby.id,
+            title: 'A New Hope',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('setOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('setOne (update)', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setOne(draft, {
+          id: TheHobbit.id,
+          title: 'Silmarillion',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['th'],
+      })
+    })
+
+    test('setMany', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setMany(draft, [
+          {
+            id: TheHobbit.id,
+            title: 'Silmarillion',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['af', 'th'],
+      })
+    })
+
+    test('removeOne', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeOne(draft, TheGreatGatsby.id)
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+        },
+        ids: ['af'],
+      })
+    })
+
+    test('removeMany', () => {
+      const withThree = adapter.addMany(state, [
+        TheGreatGatsby,
+        AnimalFarm,
+        AClockworkOrange,
+      ])
+      const result = createNextState(withThree, (draft) => {
+        adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])
+      })
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'A Clockwork Orange',
+          },
+        },
+        ids: ['aco'],
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/state_adapter.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,61 @@
+import type { EntityAdapter } from '../index'
+import { createEntityAdapter } from '../index'
+import type { PayloadAction } from '../../createAction'
+import { configureStore } from '../../configureStore'
+import { createSlice } from '../../createSlice'
+import type { BookModel } from './fixtures/book'
+
+describe('createStateOperator', () => {
+  let adapter: EntityAdapter<BookModel, string>
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+    })
+  })
+  it('Correctly mutates a draft state when inside `createNextState', () => {
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        // We should be able to call an adapter method as a mutating helper in a larger reducer
+        addOne(state, action: PayloadAction<BookModel>) {
+          // Originally, having nested `produce` calls don't mutate `state` here as I would have expected.
+          // (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
+          // One woarkound was to return the new plain result value instead
+          // See https://github.com/immerjs/immer/issues/533
+          // However, after tweaking `createStateOperator` to check if the argument is a draft,
+          // we can just treat the operator as strictly mutating, without returning a result,
+          // and the result should be correct.
+          const result = adapter.addOne(state, action)
+          expect(result.ids.length).toBe(1)
+          //Deliberately _don't_ return result
+        },
+        // We should also be able to pass them individually as case reducers
+        addAnother: adapter.addOne,
+      },
+    })
+
+    const { addOne, addAnother } = booksSlice.actions
+
+    const store = configureStore({
+      reducer: {
+        books: booksSlice.reducer,
+      },
+    })
+
+    const book1: BookModel = { id: 'a', title: 'First' }
+    store.dispatch(addOne(book1))
+
+    const state1 = store.getState()
+    expect(state1.books.ids.length).toBe(1)
+    expect(state1.books.entities['a']).toBe(book1)
+
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    store.dispatch(addAnother(book2))
+
+    const state2 = store.getState()
+    expect(state2.books.ids.length).toBe(2)
+    expect(state2.books.entities['b']).toBe(book2)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/state_selectors.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/state_selectors.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/state_selectors.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,154 @@
+import { createDraftSafeSelectorCreator } from '../../createDraftSafeSelector'
+import type { EntityAdapter, EntityState } from '../index'
+import { createEntityAdapter } from '../index'
+import type { EntitySelectors } from '../models'
+import type { BookModel } from './fixtures/book'
+import { AClockworkOrange, AnimalFarm, TheGreatGatsby } from './fixtures/book'
+import type { Selector } from 'reselect'
+import { createSelector, weakMapMemoize } from 'reselect'
+import { vi } from 'vitest'
+
+describe('Entity State Selectors', () => {
+  describe('Composed Selectors', () => {
+    interface State {
+      books: EntityState<BookModel, string>
+    }
+
+    let adapter: EntityAdapter<BookModel, string>
+    let selectors: EntitySelectors<BookModel, State, string>
+    let state: State
+
+    beforeEach(() => {
+      adapter = createEntityAdapter({
+        selectId: (book: BookModel) => book.id,
+      })
+
+      state = {
+        books: adapter.setAll(adapter.getInitialState(), [
+          AClockworkOrange,
+          AnimalFarm,
+          TheGreatGatsby,
+        ]),
+      }
+
+      selectors = adapter.getSelectors((state: State) => state.books)
+    })
+
+    it('should create a selector for selecting the ids', () => {
+      const ids = selectors.selectIds(state)
+
+      expect(ids).toEqual(state.books.ids)
+    })
+
+    it('should create a selector for selecting the entities', () => {
+      const entities = selectors.selectEntities(state)
+
+      expect(entities).toEqual(state.books.entities)
+    })
+
+    it('should create a selector for selecting the list of models', () => {
+      const models = selectors.selectAll(state)
+
+      expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
+    })
+
+    it('should create a selector for selecting the count of models', () => {
+      const total = selectors.selectTotal(state)
+
+      expect(total).toEqual(3)
+    })
+
+    it('should create a selector for selecting a single item by ID', () => {
+      const first = selectors.selectById(state, AClockworkOrange.id)
+      expect(first).toBe(AClockworkOrange)
+      const second = selectors.selectById(state, AnimalFarm.id)
+      expect(second).toBe(AnimalFarm)
+    })
+  })
+
+  describe('Uncomposed Selectors', () => {
+    type State = EntityState<BookModel, string>
+
+    let adapter: EntityAdapter<BookModel, string>
+    let selectors: EntitySelectors<
+      BookModel,
+      EntityState<BookModel, string>,
+      string
+    >
+    let state: State
+
+    beforeEach(() => {
+      adapter = createEntityAdapter({
+        selectId: (book: BookModel) => book.id,
+      })
+
+      state = adapter.setAll(adapter.getInitialState(), [
+        AClockworkOrange,
+        AnimalFarm,
+        TheGreatGatsby,
+      ])
+
+      selectors = adapter.getSelectors()
+    })
+
+    it('should create a selector for selecting the ids', () => {
+      const ids = selectors.selectIds(state)
+
+      expect(ids).toEqual(state.ids)
+    })
+
+    it('should create a selector for selecting the entities', () => {
+      const entities = selectors.selectEntities(state)
+
+      expect(entities).toEqual(state.entities)
+    })
+
+    it('should type single entity from Dictionary as entity type or undefined', () => {
+      expectType<
+        Selector<EntityState<BookModel, string>, BookModel | undefined>
+      >(createSelector(selectors.selectEntities, (entities) => entities[0]))
+    })
+
+    it('should create a selector for selecting the list of models', () => {
+      const models = selectors.selectAll(state)
+
+      expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])
+    })
+
+    it('should create a selector for selecting the count of models', () => {
+      const total = selectors.selectTotal(state)
+
+      expect(total).toEqual(3)
+    })
+
+    it('should create a selector for selecting a single item by ID', () => {
+      const first = selectors.selectById(state, AClockworkOrange.id)
+      expect(first).toBe(AClockworkOrange)
+      const second = selectors.selectById(state, AnimalFarm.id)
+      expect(second).toBe(AnimalFarm)
+    })
+  })
+  describe('custom createSelector instance', () => {
+    it('should use the custom createSelector function if provided', () => {
+      const memoizeSpy = vi.fn(
+        // test that we're allowed to pass memoizers with different options, as long as they're optional
+        <F extends (...args: any[]) => any>(fn: F, param?: boolean) => fn,
+      )
+      const createCustomSelector = createDraftSafeSelectorCreator(memoizeSpy)
+
+      const adapter = createEntityAdapter({
+        selectId: (book: BookModel) => book.id,
+      })
+
+      adapter.getSelectors(undefined, { createSelector: createCustomSelector })
+
+      expect(memoizeSpy).toHaveBeenCalled()
+
+      memoizeSpy.mockClear()
+    })
+  })
+})
+
+function expectType<T>(t: T) {
+  return t
+}
Index: node_modules/@reduxjs/toolkit/src/entities/tests/unsorted_state_adapter.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/unsorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/unsorted_state_adapter.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,759 @@
+import type { EntityAdapter, EntityState } from '../models'
+import { createEntityAdapter } from '../create_adapter'
+import type { BookModel } from './fixtures/book'
+import {
+  TheGreatGatsby,
+  AClockworkOrange,
+  AnimalFarm,
+  TheHobbit,
+} from './fixtures/book'
+import { createNextState } from '../..'
+
+describe('Unsorted State Adapter', () => {
+  let adapter: EntityAdapter<BookModel, string>
+  let state: EntityState<BookModel, string>
+
+  beforeAll(() => {
+    //eslint-disable-next-line
+    Object.defineProperty(Array.prototype, 'unwantedField', {
+      enumerable: true,
+      configurable: true,
+      value: 'This should not appear anywhere',
+    })
+  })
+
+  afterAll(() => {
+    delete (Array.prototype as any).unwantedField
+  })
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+    })
+
+    state = { ids: [], entities: {} }
+  })
+
+  it('should let you add one entity to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should not change state if you attempt to re-add an entity', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const readded = adapter.addOne(withOneEntity, TheGreatGatsby)
+
+    expect(readded).toBe(withOneEntity)
+  })
+
+  it('should let you add many entities to the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withManyMore).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add many entities to the state from a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withManyMore = adapter.addMany(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withManyMore).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add the only first occurrence for duplicate ids', () => {
+    const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
+    const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
+    const withOne = adapter.setAll(state, [TheGreatGatsby])
+    const withMany = adapter.addMany(withOne, [
+      { ...AClockworkOrange, ...firstEntry }, {...AClockworkOrange, ...secondEntry}
+    ])
+
+    expect(withMany).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...firstEntry,
+        },
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, [
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should remove existing and add new ones on setAll when passing in a dictionary', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withAll = adapter.setAll(withOneEntity, {
+      [AClockworkOrange.id]: AClockworkOrange,
+      [AnimalFarm.id]: AnimalFarm,
+    })
+
+    expect(withAll).toEqual({
+      ids: [AClockworkOrange.id, AnimalFarm.id],
+      entities: {
+        [AClockworkOrange.id]: AClockworkOrange,
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you add remove an entity from the state', () => {
+    const withOneEntity = adapter.addOne(state, TheGreatGatsby)
+
+    const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)
+
+    expect(withoutOne).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you remove many entities by id from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutMany = adapter.removeMany(withAll, [
+      TheGreatGatsby.id,
+      AClockworkOrange.id,
+    ])
+
+    expect(withoutMany).toEqual({
+      ids: [AnimalFarm.id],
+      entities: {
+        [AnimalFarm.id]: AnimalFarm,
+      },
+    })
+  })
+
+  it('should let you remove all entities from the state', () => {
+    const withAll = adapter.setAll(state, [
+      TheGreatGatsby,
+      AClockworkOrange,
+      AnimalFarm,
+    ])
+
+    const withoutAll = adapter.removeAll(withAll)
+
+    expect(withoutAll).toEqual({
+      ids: [],
+      entities: {},
+    })
+  })
+
+  it('should let you update an entity in the state', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should not change state if you attempt to update an entity that has not been added', () => {
+    const withUpdates = adapter.updateOne(state, {
+      id: TheGreatGatsby.id,
+      changes: { title: 'A New Title' },
+    })
+
+    expect(withUpdates).toBe(state)
+  })
+
+  it('should not change ids state if you attempt to update an entity that has already been added', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withOne.ids).toBe(withUpdates.ids)
+  })
+
+  it('should let you update the id of entity', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { id: 'A New Id' }
+
+    const withUpdates = adapter.updateOne(withOne, {
+      id: TheGreatGatsby.id,
+      changes,
+    })
+
+    expect(withUpdates).toEqual({
+      ids: [changes.id],
+      entities: {
+        [changes.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should let you update many entities by id in the state', () => {
+    const firstChange = { title: 'First Change' }
+    const secondChange = { title: 'Second Change' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])
+
+    const withUpdates = adapter.updateMany(withMany, [
+      { id: TheGreatGatsby.id, changes: firstChange },
+      { id: AClockworkOrange.id, changes: secondChange },
+    ])
+
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...secondChange,
+        },
+      },
+    })
+  })
+
+  it("doesn't break when multiple renames of one item occur", () => {
+    const withA = adapter.addOne(state, { id: 'a', title: 'First' })
+
+    const withUpdates = adapter.updateMany(withA, [
+      { id: 'a', changes: { id: 'b' } },
+      { id: 'a', changes: { id: 'c' } },
+    ])
+
+    const { ids, entities } = withUpdates
+
+    /*
+      Original code failed with a mish-mash of values, like:
+      {
+        ids: [ 'c' ],
+        entities: { b: { id: 'b', title: 'First' }, c: { id: 'c' } }
+      }
+      We now expect that only 'c' will be left:
+      { 
+        ids: [ 'c' ], 
+        entities: { c: { id: 'c', title: 'First' } } 
+      }
+    */
+    expect(ids.length).toBe(1)
+    expect(ids).toEqual(['c'])
+    expect(entities.a).toBeFalsy()
+    expect(entities.b).toBeFalsy()
+    expect(entities.c).toBeTruthy()
+  })
+
+  it('should let you add one entity to the state with upsert()', () => {
+    const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)
+    expect(withOneEntity).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you update an entity in the state with upsert()', () => {
+    const withOne = adapter.addOne(state, TheGreatGatsby)
+    const changes = { title: 'A New Hope' }
+
+    const withUpdates = adapter.upsertOne(withOne, {
+      ...TheGreatGatsby,
+      ...changes,
+    })
+    expect(withUpdates).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...changes,
+        },
+      },
+    })
+  })
+
+  it('should let you upsert many entities in the state', () => {
+    const firstChange = { title: 'First Change' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      { ...TheGreatGatsby, ...firstChange },
+      AClockworkOrange,
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you upsert many entities in the state when passing in a dictionary', () => {
+    const firstChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, {
+      [TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: {
+          ...TheGreatGatsby,
+          ...firstChange,
+        },
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you add a new entity then apply changes to it', () => {
+    const firstChange = { author: TheHobbit.author }
+    const secondChange = { title: 'Zack' }
+    const withMany = adapter.setAll(state, [TheGreatGatsby])
+
+    const withUpserts = adapter.upsertMany(withMany, [
+      {...AClockworkOrange}, { ...AClockworkOrange, ...firstChange }, {...AClockworkOrange, ...secondChange}
+    ])
+
+    expect(withUpserts).toEqual({
+      ids: [TheGreatGatsby.id, AClockworkOrange.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+        [AClockworkOrange.id]: {
+          ...AClockworkOrange,
+          ...firstChange,
+          ...secondChange,
+        },
+      },
+    })
+  })
+
+  it('should let you add a new entity in the state with setOne()', () => {
+    const withOne = adapter.setOne(state, TheGreatGatsby)
+    expect(withOne).toEqual({
+      ids: [TheGreatGatsby.id],
+      entities: {
+        [TheGreatGatsby.id]: TheGreatGatsby,
+      },
+    })
+  })
+
+  it('should let you replace an entity in the state with setOne()', () => {
+    let withOne = adapter.setOne(state, TheHobbit)
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    withOne = adapter.setOne(withOne, changeWithoutAuthor)
+
+    expect(withOne).toEqual({
+      ids: [TheHobbit.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+      },
+    })
+  })
+
+  it('should let you set many entities in the state', () => {
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, [
+      changeWithoutAuthor,
+      AClockworkOrange,
+    ])
+
+    expect(withSetMany).toEqual({
+      ids: [TheHobbit.id, AClockworkOrange.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+
+  it('should let you set many entities in the state when passing in a dictionary', () => {
+    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
+    const withMany = adapter.setAll(state, [TheHobbit])
+
+    const withSetMany = adapter.setMany(withMany, {
+      [TheHobbit.id]: changeWithoutAuthor,
+      [AClockworkOrange.id]: AClockworkOrange,
+    })
+
+    expect(withSetMany).toEqual({
+      ids: [TheHobbit.id, AClockworkOrange.id],
+      entities: {
+        [TheHobbit.id]: changeWithoutAuthor,
+        [AClockworkOrange.id]: AClockworkOrange,
+      },
+    })
+  })
+  it("only returns one entry for that id in the id's array", () => {
+    const book1: BookModel = { id: 'a', title: 'First' }
+    const book2: BookModel = { id: 'b', title: 'Second' }
+    const initialState = adapter.getInitialState()
+    const withItems = adapter.addMany(initialState, [book1, book2])
+
+    expect(withItems.ids).toEqual(['a', 'b'])
+    const withUpdate = adapter.updateOne(withItems, {
+      id: 'a',
+      changes: { id: 'b' },
+    })
+
+    expect(withUpdate.ids).toEqual(['b'])
+    expect(withUpdate.entities['b']!.title).toBe(book1.title)
+  })
+
+  describe('can be used mutably when wrapped in createNextState', () => {
+    test('removeAll', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeAll(draft)
+      })
+      expect(result).toEqual({
+        entities: {},
+        ids: [],
+      })
+    })
+
+    test('addOne', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addOne(draft, TheGreatGatsby)
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('addMany', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('setAll', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('updateOne', () => {
+      const withOne = adapter.addOne(state, TheGreatGatsby)
+      const changes = { title: 'A New Hope' }
+      const result = createNextState(withOne, (draft) => {
+        adapter.updateOne(draft, {
+          id: TheGreatGatsby.id,
+          changes,
+        })
+      })
+
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('updateMany', () => {
+      const firstChange = { title: 'First Change' }
+      const secondChange = { title: 'Second Change' }
+      const thirdChange = { title: 'Third Change' }
+      const fourthChange = { author: 'Fourth Change' }
+      const withMany = adapter.setAll(state, [
+        TheGreatGatsby,
+        AClockworkOrange,
+        TheHobbit,
+      ])
+
+      const result = createNextState(withMany, (draft) => {
+        adapter.updateMany(draft, [
+          { id: TheHobbit.id, changes: firstChange },
+          { id: TheGreatGatsby.id, changes: secondChange },
+          { id: AClockworkOrange.id, changes: thirdChange },
+          { id: TheHobbit.id, changes: fourthChange },
+        ])
+      })
+
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'Third Change',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'Second Change',
+          },
+          th: {
+            author: 'Fourth Change',
+            id: 'th',
+            title: 'First Change',
+          },
+        },
+        ids: ['tgg', 'aco', 'th'],
+      })
+    })
+
+    test('upsertOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.upsertOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertOne (update)', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertOne(draft, {
+          id: TheGreatGatsby.id,
+          title: 'A New Hope',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('upsertMany', () => {
+      const withOne = adapter.upsertOne(state, TheGreatGatsby)
+      const result = createNextState(withOne, (draft) => {
+        adapter.upsertMany(draft, [
+          {
+            id: TheGreatGatsby.id,
+            title: 'A New Hope',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          tgg: {
+            id: 'tgg',
+            title: 'A New Hope',
+          },
+        },
+        ids: ['tgg', 'af'],
+      })
+    })
+
+    test('setOne (insert)', () => {
+      const result = createNextState(state, (draft) => {
+        adapter.setOne(draft, TheGreatGatsby)
+      })
+      expect(result).toEqual({
+        entities: {
+          tgg: {
+            id: 'tgg',
+            title: 'The Great Gatsby',
+          },
+        },
+        ids: ['tgg'],
+      })
+    })
+
+    test('setOne (update)', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setOne(draft, {
+          id: TheHobbit.id,
+          title: 'Silmarillion',
+        })
+      })
+      expect(result).toEqual({
+        entities: {
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['th'],
+      })
+    })
+
+    test('setMany', () => {
+      const withOne = adapter.setOne(state, TheHobbit)
+      const result = createNextState(withOne, (draft) => {
+        adapter.setMany(draft, [
+          {
+            id: TheHobbit.id,
+            title: 'Silmarillion',
+          },
+          AnimalFarm,
+        ])
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+          th: {
+            id: 'th',
+            title: 'Silmarillion',
+          },
+        },
+        ids: ['th', 'af'],
+      })
+    })
+
+    test('removeOne', () => {
+      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])
+      const result = createNextState(withTwo, (draft) => {
+        adapter.removeOne(draft, TheGreatGatsby.id)
+      })
+      expect(result).toEqual({
+        entities: {
+          af: {
+            id: 'af',
+            title: 'Animal Farm',
+          },
+        },
+        ids: ['af'],
+      })
+    })
+
+    test('removeMany', () => {
+      const withThree = adapter.addMany(state, [
+        TheGreatGatsby,
+        AnimalFarm,
+        AClockworkOrange,
+      ])
+      const result = createNextState(withThree, (draft) => {
+        adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])
+      })
+      expect(result).toEqual({
+        entities: {
+          aco: {
+            id: 'aco',
+            title: 'A Clockwork Orange',
+          },
+        },
+        ids: ['aco'],
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/tests/utils.spec.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/tests/utils.spec.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/tests/utils.spec.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,71 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { AClockworkOrange } from './fixtures/book'
+
+describe('Entity utils', () => {
+  describe(`selectIdValue()`, () => {
+    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+    beforeEach(() => {
+      vi.resetModules() // this is important - it clears the cache
+      vi.stubEnv('NODE_ENV', 'development')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+      vi.clearAllMocks()
+    })
+
+    afterAll(() => {
+      vi.restoreAllMocks()
+    })
+
+    it('should not warn when key does exist', async () => {
+      const { selectIdValue } = await import('../utils')
+
+      selectIdValue(AClockworkOrange, (book: any) => book.id)
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    })
+
+    it('should warn when key does not exist in dev mode', async () => {
+      const { selectIdValue } = await import('../utils')
+
+      expect(process.env.NODE_ENV).toBe('development')
+
+      selectIdValue(AClockworkOrange, (book: any) => book.foo)
+
+      expect(consoleWarnSpy).toHaveBeenCalledOnce()
+    })
+
+    it('should warn when key is undefined in dev mode', async () => {
+      const { selectIdValue } = await import('../utils')
+
+      expect(process.env.NODE_ENV).toBe('development')
+
+      const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
+      selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
+
+      expect(consoleWarnSpy).toHaveBeenCalledOnce()
+    })
+
+    it('should not warn when key does not exist in prod mode', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { selectIdValue } = await import('../utils')
+
+      selectIdValue(AClockworkOrange, (book: any) => book.foo)
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    })
+
+    it('should not warn when key is undefined in prod mode', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { selectIdValue } = await import('../utils')
+
+      const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }
+      selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,204 @@
+import type { Draft } from 'immer'
+import type {
+  EntityStateAdapter,
+  IdSelector,
+  Update,
+  EntityId,
+  DraftableEntityState,
+} from './models'
+import {
+  createStateOperator,
+  createSingleArgumentStateOperator,
+} from './state_adapter'
+import {
+  selectIdValue,
+  ensureEntitiesArray,
+  splitAddedUpdatedEntities,
+} from './utils'
+
+export function createUnsortedStateAdapter<T, Id extends EntityId>(
+  selectId: IdSelector<T, Id>,
+): EntityStateAdapter<T, Id> {
+  type R = DraftableEntityState<T, Id>
+
+  function addOneMutably(entity: T, state: R): void {
+    const key = selectIdValue(entity, selectId)
+
+    if (key in state.entities) {
+      return
+    }
+
+    state.ids.push(key as Id & Draft<Id>)
+    ;(state.entities as Record<Id, T>)[key] = entity
+  }
+
+  function addManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+
+    for (const entity of newEntities) {
+      addOneMutably(entity, state)
+    }
+  }
+
+  function setOneMutably(entity: T, state: R): void {
+    const key = selectIdValue(entity, selectId)
+    if (!(key in state.entities)) {
+      state.ids.push(key as Id & Draft<Id>)
+    }
+    ;(state.entities as Record<Id, T>)[key] = entity
+  }
+
+  function setManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+    for (const entity of newEntities) {
+      setOneMutably(entity, state)
+    }
+  }
+
+  function setAllMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    newEntities = ensureEntitiesArray(newEntities)
+
+    state.ids = []
+    state.entities = {} as Record<Id, T>
+
+    addManyMutably(newEntities, state)
+  }
+
+  function removeOneMutably(key: Id, state: R): void {
+    return removeManyMutably([key], state)
+  }
+
+  function removeManyMutably(keys: readonly Id[], state: R): void {
+    let didMutate = false
+
+    keys.forEach((key) => {
+      if (key in state.entities) {
+        delete (state.entities as Record<Id, T>)[key]
+        didMutate = true
+      }
+    })
+
+    if (didMutate) {
+      state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as
+        | Id[]
+        | Draft<Id[]>
+    }
+  }
+
+  function removeAllMutably(state: R): void {
+    Object.assign(state, {
+      ids: [],
+      entities: {},
+    })
+  }
+
+  function takeNewKey(
+    keys: { [id: string]: Id },
+    update: Update<T, Id>,
+    state: R,
+  ): boolean {
+    const original: T | undefined = (state.entities as Record<Id, T>)[update.id]
+    if (original === undefined) {
+      return false
+    }
+    const updated: T = Object.assign({}, original, update.changes)
+    const newKey = selectIdValue(updated, selectId)
+    const hasNewKey = newKey !== update.id
+
+    if (hasNewKey) {
+      keys[update.id] = newKey
+      delete (state.entities as Record<Id, T>)[update.id]
+    }
+
+    ;(state.entities as Record<Id, T>)[newKey] = updated
+
+    return hasNewKey
+  }
+
+  function updateOneMutably(update: Update<T, Id>, state: R): void {
+    return updateManyMutably([update], state)
+  }
+
+  function updateManyMutably(
+    updates: ReadonlyArray<Update<T, Id>>,
+    state: R,
+  ): void {
+    const newKeys: { [id: string]: Id } = {}
+
+    const updatesPerEntity: { [id: string]: Update<T, Id> } = {}
+
+    updates.forEach((update) => {
+      // Only apply updates to entities that currently exist
+      if (update.id in state.entities) {
+        // If there are multiple updates to one entity, merge them together
+        updatesPerEntity[update.id] = {
+          id: update.id,
+          // Spreads ignore falsy values, so this works even if there isn't
+          // an existing update already at this key
+          changes: {
+            ...updatesPerEntity[update.id]?.changes,
+            ...update.changes,
+          },
+        }
+      }
+    })
+
+    updates = Object.values(updatesPerEntity)
+
+    const didMutateEntities = updates.length > 0
+
+    if (didMutateEntities) {
+      const didMutateIds =
+        updates.filter((update) => takeNewKey(newKeys, update, state)).length >
+        0
+
+      if (didMutateIds) {
+        state.ids = Object.values(state.entities).map((e) =>
+          selectIdValue(e as T, selectId),
+        )
+      }
+    }
+  }
+
+  function upsertOneMutably(entity: T, state: R): void {
+    return upsertManyMutably([entity], state)
+  }
+
+  function upsertManyMutably(
+    newEntities: readonly T[] | Record<Id, T>,
+    state: R,
+  ): void {
+    const [added, updated] = splitAddedUpdatedEntities<T, Id>(
+      newEntities,
+      selectId,
+      state,
+    )
+
+    addManyMutably(added, state)
+    updateManyMutably(updated, state)
+  }
+
+  return {
+    removeAll: createSingleArgumentStateOperator(removeAllMutably),
+    addOne: createStateOperator(addOneMutably),
+    addMany: createStateOperator(addManyMutably),
+    setOne: createStateOperator(setOneMutably),
+    setMany: createStateOperator(setManyMutably),
+    setAll: createStateOperator(setAllMutably),
+    updateOne: createStateOperator(updateOneMutably),
+    updateMany: createStateOperator(updateManyMutably),
+    upsertOne: createStateOperator(upsertOneMutably),
+    upsertMany: createStateOperator(upsertManyMutably),
+    removeOne: createStateOperator(removeOneMutably),
+    removeMany: createStateOperator(removeManyMutably),
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/entities/utils.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/entities/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/entities/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,68 @@
+import type { Draft } from 'immer'
+import { current, isDraft } from '../immerImports'
+import type {
+  DraftableEntityState,
+  EntityId,
+  IdSelector,
+  Update,
+} from './models'
+
+export function selectIdValue<T, Id extends EntityId>(
+  entity: T,
+  selectId: IdSelector<T, Id>,
+) {
+  const key = selectId(entity)
+
+  if (process.env.NODE_ENV !== 'production' && key === undefined) {
+    console.warn(
+      'The entity passed to the `selectId` implementation returned undefined.',
+      'You should probably provide your own `selectId` implementation.',
+      'The entity that was passed:',
+      entity,
+      'The `selectId` implementation:',
+      selectId.toString(),
+    )
+  }
+
+  return key
+}
+
+export function ensureEntitiesArray<T, Id extends EntityId>(
+  entities: readonly T[] | Record<Id, T>,
+): readonly T[] {
+  if (!Array.isArray(entities)) {
+    entities = Object.values(entities)
+  }
+
+  return entities
+}
+
+export function getCurrent<T>(value: T | Draft<T>): T {
+  return (isDraft(value) ? current(value) : value) as T
+}
+
+export function splitAddedUpdatedEntities<T, Id extends EntityId>(
+  newEntities: readonly T[] | Record<Id, T>,
+  selectId: IdSelector<T, Id>,
+  state: DraftableEntityState<T, Id>,
+): [T[], Update<T, Id>[], Id[]] {
+  newEntities = ensureEntitiesArray(newEntities)
+
+  const existingIdsArray = getCurrent(state.ids)
+  const existingIds = new Set<Id>(existingIdsArray)
+
+  const added: T[] = []
+  const addedIds = new Set<Id>([])
+  const updated: Update<T, Id>[] = []
+
+  for (const entity of newEntities) {
+    const id = selectIdValue(entity, selectId)
+    if (existingIds.has(id) || addedIds.has(id)) {
+      updated.push({ id, changes: entity })
+    } else {
+      addedIds.add(id)
+      added.push(entity)
+    }
+  }
+  return [added, updated, existingIdsArray]
+}
Index: node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+/**
+ * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
+ *
+ * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
+ * during build.
+ * @param {number} code
+ */
+export function formatProdErrorMessage(code: number) {
+  return (
+    `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` +
+    'use the non-minified dev environment for full errors. '
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,31 @@
+import type { StoreEnhancer } from 'redux'
+import type { AutoBatchOptions } from './autoBatchEnhancer'
+import { autoBatchEnhancer } from './autoBatchEnhancer'
+import { Tuple } from './utils'
+import type { Middlewares } from './configureStore'
+import type { ExtractDispatchExtensions } from './tsHelpers'
+
+type GetDefaultEnhancersOptions = {
+  autoBatch?: boolean | AutoBatchOptions
+}
+
+export type GetDefaultEnhancers<M extends Middlewares<any>> = (
+  options?: GetDefaultEnhancersOptions,
+) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>
+
+export const buildGetDefaultEnhancers = <M extends Middlewares<any>>(
+  middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>,
+): GetDefaultEnhancers<M> =>
+  function getDefaultEnhancers(options) {
+    const { autoBatch = true } = options ?? {}
+
+    let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer)
+    if (autoBatch) {
+      enhancerArray.push(
+        autoBatchEnhancer(
+          typeof autoBatch === 'object' ? autoBatch : undefined,
+        ),
+      )
+    }
+    return enhancerArray as any
+  }
Index: node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,113 @@
+import type { Middleware, UnknownAction } from 'redux'
+import type { ThunkMiddleware } from 'redux-thunk'
+import { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk'
+import type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
+import { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
+import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'
+/* PROD_START_REMOVE_UMD */
+import { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'
+/* PROD_STOP_REMOVE_UMD */
+
+import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'
+import { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'
+import type { ExcludeFromTuple } from './tsHelpers'
+import { Tuple } from './utils'
+
+function isBoolean(x: any): x is boolean {
+  return typeof x === 'boolean'
+}
+
+interface ThunkOptions<E = any> {
+  extraArgument: E
+}
+
+interface GetDefaultMiddlewareOptions {
+  thunk?: boolean | ThunkOptions
+  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions
+  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions
+  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions
+}
+
+export type ThunkMiddlewareFor<
+  S,
+  O extends GetDefaultMiddlewareOptions = {},
+> = O extends {
+  thunk: false
+}
+  ? never
+  : O extends { thunk: { extraArgument: infer E } }
+    ? ThunkMiddleware<S, UnknownAction, E>
+    : ThunkMiddleware<S, UnknownAction>
+
+export type GetDefaultMiddleware<S = any> = <
+  O extends GetDefaultMiddlewareOptions = {
+    thunk: true
+    immutableCheck: true
+    serializableCheck: true
+    actionCreatorCheck: true
+  },
+>(
+  options?: O,
+) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>
+
+export const buildGetDefaultMiddleware = <S = any>(): GetDefaultMiddleware<S> =>
+  function getDefaultMiddleware(options) {
+    const {
+      thunk = true,
+      immutableCheck = true,
+      serializableCheck = true,
+      actionCreatorCheck = true,
+    } = options ?? {}
+
+    let middlewareArray = new Tuple<Middleware[]>()
+
+    if (thunk) {
+      if (isBoolean(thunk)) {
+        middlewareArray.push(thunkMiddleware)
+      } else {
+        middlewareArray.push(withExtraArgument(thunk.extraArgument))
+      }
+    }
+
+    if (process.env.NODE_ENV !== 'production') {
+      if (immutableCheck) {
+        /* PROD_START_REMOVE_UMD */
+        let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}
+
+        if (!isBoolean(immutableCheck)) {
+          immutableOptions = immutableCheck
+        }
+
+        middlewareArray.unshift(
+          createImmutableStateInvariantMiddleware(immutableOptions),
+        )
+        /* PROD_STOP_REMOVE_UMD */
+      }
+
+      if (serializableCheck) {
+        let serializableOptions: SerializableStateInvariantMiddlewareOptions =
+          {}
+
+        if (!isBoolean(serializableCheck)) {
+          serializableOptions = serializableCheck
+        }
+
+        middlewareArray.push(
+          createSerializableStateInvariantMiddleware(serializableOptions),
+        )
+      }
+      if (actionCreatorCheck) {
+        let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}
+
+        if (!isBoolean(actionCreatorCheck)) {
+          actionCreatorOptions = actionCreatorCheck
+        }
+
+        middlewareArray.unshift(
+          createActionCreatorInvariantMiddleware(actionCreatorOptions),
+        )
+      }
+    }
+
+    return middlewareArray as any
+  }
Index: node_modules/@reduxjs/toolkit/src/immerImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,7 @@
+export {
+  current,
+  isDraft,
+  produce as createNextState,
+  isDraftable,
+  setUseStrictIteration,
+} from 'immer'
Index: node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,274 @@
+import type { Middleware } from 'redux'
+import type { IgnorePaths } from './serializableStateInvariantMiddleware'
+import { getTimeMeasureUtils } from './utils'
+
+type EntryProcessor = (key: string, value: any) => any
+
+/**
+ * The default `isImmutable` function.
+ *
+ * @public
+ */
+export function isImmutableDefault(value: unknown): boolean {
+  return typeof value !== 'object' || value == null || Object.isFrozen(value)
+}
+
+export function trackForMutations(
+  isImmutable: IsImmutableFunc,
+  ignoredPaths: IgnorePaths | undefined,
+  obj: any,
+) {
+  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj)
+  return {
+    detectMutations() {
+      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj)
+    },
+  }
+}
+
+interface TrackedProperty {
+  value: any
+  children: Record<string, any>
+}
+
+function trackProperties(
+  isImmutable: IsImmutableFunc,
+  ignoredPaths: IgnorePaths = [],
+  obj: Record<string, any>,
+  path: string = '',
+  checkedObjects: Set<Record<string, any>> = new Set(),
+) {
+  const tracked: Partial<TrackedProperty> = { value: obj }
+
+  if (!isImmutable(obj) && !checkedObjects.has(obj)) {
+    checkedObjects.add(obj)
+    tracked.children = {}
+
+    const hasIgnoredPaths = ignoredPaths.length > 0
+
+    for (const key in obj) {
+      const nestedPath = path ? path + '.' + key : key
+
+      if (hasIgnoredPaths) {
+        const hasMatches = ignoredPaths.some((ignored) => {
+          if (ignored instanceof RegExp) {
+            return ignored.test(nestedPath)
+          }
+          return nestedPath === ignored
+        })
+        if (hasMatches) {
+          continue
+        }
+      }
+
+      tracked.children[key] = trackProperties(
+        isImmutable,
+        ignoredPaths,
+        obj[key],
+        nestedPath,
+      )
+    }
+  }
+  return tracked as TrackedProperty
+}
+
+function detectMutations(
+  isImmutable: IsImmutableFunc,
+  ignoredPaths: IgnorePaths = [],
+  trackedProperty: TrackedProperty,
+  obj: any,
+  sameParentRef: boolean = false,
+  path: string = '',
+): { wasMutated: boolean; path?: string } {
+  const prevObj = trackedProperty ? trackedProperty.value : undefined
+
+  const sameRef = prevObj === obj
+
+  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
+    return { wasMutated: true, path }
+  }
+
+  if (isImmutable(prevObj) || isImmutable(obj)) {
+    return { wasMutated: false }
+  }
+
+  // Gather all keys from prev (tracked) and after objs
+  const keysToDetect: Record<string, boolean> = {}
+  for (let key in trackedProperty.children) {
+    keysToDetect[key] = true
+  }
+  for (let key in obj) {
+    keysToDetect[key] = true
+  }
+
+  const hasIgnoredPaths = ignoredPaths.length > 0
+
+  for (let key in keysToDetect) {
+    const nestedPath = path ? path + '.' + key : key
+
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath)
+        }
+        return nestedPath === ignored
+      })
+      if (hasMatches) {
+        continue
+      }
+    }
+
+    const result = detectMutations(
+      isImmutable,
+      ignoredPaths,
+      trackedProperty.children[key],
+      obj[key],
+      sameRef,
+      nestedPath,
+    )
+
+    if (result.wasMutated) {
+      return result
+    }
+  }
+  return { wasMutated: false }
+}
+
+type IsImmutableFunc = (value: any) => boolean
+
+/**
+ * Options for `createImmutableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+export interface ImmutableStateInvariantMiddlewareOptions {
+  /**
+    Callback function to check if a value is considered to be immutable.
+    This function is applied recursively to every value contained in the state.
+    The default implementation will return true for primitive types
+    (like numbers, strings, booleans, null and undefined).
+   */
+  isImmutable?: IsImmutableFunc
+  /**
+    An array of dot-separated path strings that match named nodes from
+    the root state to ignore when checking for immutability.
+    Defaults to undefined
+   */
+  ignoredPaths?: IgnorePaths
+  /** Print a warning if checks take longer than N ms. Default: 32ms */
+  warnAfter?: number
+}
+
+/**
+ * Creates a middleware that checks whether any state was mutated in between
+ * dispatches or during a dispatch. If any mutations are detected, an error is
+ * thrown.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+export function createImmutableStateInvariantMiddleware(
+  options: ImmutableStateInvariantMiddlewareOptions = {},
+): Middleware {
+  if (process.env.NODE_ENV === 'production') {
+    return () => (next) => (action) => next(action)
+  } else {
+    function stringify(
+      obj: any,
+      serializer?: EntryProcessor,
+      indent?: string | number,
+      decycler?: EntryProcessor,
+    ): string {
+      return JSON.stringify(obj, getSerialize(serializer, decycler), indent)
+    }
+
+    function getSerialize(
+      serializer?: EntryProcessor,
+      decycler?: EntryProcessor,
+    ): EntryProcessor {
+      let stack: any[] = [],
+        keys: any[] = []
+
+      if (!decycler)
+        decycler = function (_: string, value: any) {
+          if (stack[0] === value) return '[Circular ~]'
+          return (
+            '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
+          )
+        }
+
+      return function (this: any, key: string, value: any) {
+        if (stack.length > 0) {
+          var thisPos = stack.indexOf(this)
+          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
+          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
+          if (~stack.indexOf(value)) value = decycler!.call(this, key, value)
+        } else stack.push(value)
+
+        return serializer == null ? value : serializer.call(this, key, value)
+      }
+    }
+
+    let {
+      isImmutable = isImmutableDefault,
+      ignoredPaths,
+      warnAfter = 32,
+    } = options
+
+    const track = trackForMutations.bind(null, isImmutable, ignoredPaths)
+
+    return ({ getState }) => {
+      let state = getState()
+      let tracker = track(state)
+
+      let result
+      return (next) => (action) => {
+        const measureUtils = getTimeMeasureUtils(
+          warnAfter,
+          'ImmutableStateInvariantMiddleware',
+        )
+
+        measureUtils.measureTime(() => {
+          state = getState()
+
+          result = tracker.detectMutations()
+          // Track before potentially not meeting the invariant
+          tracker = track(state)
+
+          if (result.wasMutated) {
+            throw new Error(
+              `A state mutation was detected between dispatches, in the path '${
+                result.path || ''
+              }'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
+            )
+          }
+        })
+
+        const dispatchedAction = next(action)
+
+        measureUtils.measureTime(() => {
+          state = getState()
+
+          result = tracker.detectMutations()
+          // Track before potentially not meeting the invariant
+          tracker = track(state)
+
+          if (result.wasMutated) {
+            throw new Error(
+              `A state mutation was detected inside a dispatch, in the path: ${
+                result.path || ''
+              }. Take a look at the reducer(s) handling the action ${stringify(
+                action,
+              )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
+            )
+          }
+        })
+
+        measureUtils.warnIfExceeded()
+
+        return dispatchedAction
+      }
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,213 @@
+// 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 './formatProdErrorMessage'
+
+export * from 'redux'
+export { freeze, original } from 'immer'
+export { createNextState, current, isDraft } from './immerImports'
+export type { Draft, WritableDraft } from 'immer'
+export { createSelector, lruMemoize } from 'reselect'
+export { createSelectorCreator, weakMapMemoize } from './reselectImports'
+export type { Selector, OutputSelector } from 'reselect'
+export {
+  createDraftSafeSelector,
+  createDraftSafeSelectorCreator,
+} from './createDraftSafeSelector'
+export type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'
+
+export {
+  // js
+  configureStore,
+} from './configureStore'
+export type {
+  // types
+  ConfigureStoreOptions,
+  EnhancedStore,
+} from './configureStore'
+export type { DevToolsEnhancerOptions } from './devtoolsExtension'
+export {
+  // js
+  createAction,
+  isActionCreator,
+  isFSA as isFluxStandardAction,
+} from './createAction'
+export type {
+  // types
+  PayloadAction,
+  PayloadActionCreator,
+  ActionCreatorWithNonInferrablePayload,
+  ActionCreatorWithOptionalPayload,
+  ActionCreatorWithPayload,
+  ActionCreatorWithoutPayload,
+  ActionCreatorWithPreparedPayload,
+  PrepareAction,
+} from './createAction'
+export {
+  // js
+  createReducer,
+} from './createReducer'
+export type {
+  // types
+  Actions,
+  CaseReducer,
+  CaseReducers,
+} from './createReducer'
+export {
+  // js
+  createSlice,
+  buildCreateSlice,
+  asyncThunkCreator,
+  ReducerType,
+} from './createSlice'
+
+export type {
+  // types
+  CreateSliceOptions,
+  Slice,
+  CaseReducerActions,
+  SliceCaseReducers,
+  ValidateSliceCaseReducers,
+  CaseReducerWithPrepare,
+  ReducerCreators,
+  SliceSelectors,
+} from './createSlice'
+export type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
+export { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
+export {
+  // js
+  createImmutableStateInvariantMiddleware,
+  isImmutableDefault,
+} from './immutableStateInvariantMiddleware'
+export type {
+  // types
+  ImmutableStateInvariantMiddlewareOptions,
+} from './immutableStateInvariantMiddleware'
+export {
+  // js
+  createSerializableStateInvariantMiddleware,
+  findNonSerializableValue,
+  isPlain,
+} from './serializableStateInvariantMiddleware'
+export type {
+  // types
+  SerializableStateInvariantMiddlewareOptions,
+} from './serializableStateInvariantMiddleware'
+export type {
+  // types
+  ActionReducerMapBuilder,
+  AsyncThunkReducers,
+} from './mapBuilders'
+export { Tuple } from './utils'
+
+export { createEntityAdapter } from './entities/create_adapter'
+export type {
+  EntityState,
+  EntityAdapter,
+  EntitySelectors,
+  EntityStateAdapter,
+  EntityId,
+  Update,
+  IdSelector,
+  Comparer,
+} from './entities/models'
+
+export {
+  createAsyncThunk,
+  unwrapResult,
+  miniSerializeError,
+} from './createAsyncThunk'
+export type {
+  AsyncThunk,
+  AsyncThunkConfig,
+  AsyncThunkDispatchConfig,
+  AsyncThunkOptions,
+  AsyncThunkAction,
+  AsyncThunkPayloadCreatorReturnValue,
+  AsyncThunkPayloadCreator,
+  GetState,
+  GetThunkAPI,
+  SerializedError,
+  CreateAsyncThunkFunction,
+} from './createAsyncThunk'
+
+export {
+  // js
+  isAllOf,
+  isAnyOf,
+  isPending,
+  isRejected,
+  isFulfilled,
+  isAsyncThunkAction,
+  isRejectedWithValue,
+} from './matchers'
+export type {
+  // types
+  ActionMatchingAllOf,
+  ActionMatchingAnyOf,
+} from './matchers'
+
+export { nanoid } from './nanoid'
+
+export type {
+  ListenerEffect,
+  ListenerMiddleware,
+  ListenerEffectAPI,
+  ListenerMiddlewareInstance,
+  CreateListenerMiddlewareOptions,
+  ListenerErrorHandler,
+  TypedStartListening,
+  TypedAddListener,
+  TypedStopListening,
+  TypedRemoveListener,
+  UnsubscribeListener,
+  UnsubscribeListenerOptions,
+  ForkedTaskExecutor,
+  ForkedTask,
+  ForkedTaskAPI,
+  AsyncTaskExecutor,
+  SyncTaskExecutor,
+  TaskCancelled,
+  TaskRejected,
+  TaskResolved,
+  TaskResult,
+} from './listenerMiddleware/index'
+export type { AnyListenerPredicate } from './listenerMiddleware/types'
+
+export {
+  createListenerMiddleware,
+  addListener,
+  removeListener,
+  clearAllListeners,
+  TaskAbortError,
+} from './listenerMiddleware/index'
+
+export type {
+  AddMiddleware,
+  DynamicDispatch,
+  DynamicMiddlewareInstance,
+  GetDispatchType as GetDispatch,
+  MiddlewareApiConfig,
+} from './dynamicMiddleware/types'
+export { createDynamicMiddleware } from './dynamicMiddleware/index'
+
+export {
+  SHOULD_AUTOBATCH,
+  prepareAutoBatched,
+  autoBatchEnhancer,
+} from './autoBatchEnhancer'
+export type { AutoBatchOptions } from './autoBatchEnhancer'
+
+export { combineSlices } from './combineSlices'
+
+export type {
+  CombinedSliceReducer,
+  WithSlice,
+  WithSlicePreloadedState,
+} from './combineSlices'
+
+export type {
+  ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions,
+  SafePromise,
+} from './tsHelpers'
+
+export { formatProdErrorMessage } from './formatProdErrorMessage'
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,20 @@
+import type { SerializedError } from '@reduxjs/toolkit'
+
+const task = 'task'
+const listener = 'listener'
+const completed = 'completed'
+const cancelled = 'cancelled'
+
+/* TaskAbortError error codes  */
+export const taskCancelled = `task-${cancelled}` as const
+export const taskCompleted = `task-${completed}` as const
+export const listenerCancelled = `${listener}-${cancelled}` as const
+export const listenerCompleted = `${listener}-${completed}` as const
+
+export class TaskAbortError implements SerializedError {
+  name = 'TaskAbortError'
+  message: string
+  constructor(public code: string | undefined) {
+    this.message = `${task} ${cancelled} (reason: ${code})`
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,562 @@
+import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'
+import { isAction } from '../reduxImports'
+import type { ThunkDispatch } from 'redux-thunk'
+import { createAction } from '../createAction'
+import { nanoid } from '../nanoid'
+
+import {
+  TaskAbortError,
+  listenerCancelled,
+  listenerCompleted,
+  taskCancelled,
+  taskCompleted,
+} from './exceptions'
+import {
+  createDelay,
+  createPause,
+  raceWithSignal,
+  runTask,
+  validateActive,
+} from './task'
+import type {
+  AddListenerOverloads,
+  AnyListenerPredicate,
+  CreateListenerMiddlewareOptions,
+  FallbackAddListenerOptions,
+  ForkOptions,
+  ForkedTask,
+  ForkedTaskExecutor,
+  ListenerEntry,
+  ListenerErrorHandler,
+  ListenerErrorInfo,
+  ListenerMiddleware,
+  ListenerMiddlewareInstance,
+  TakePattern,
+  TaskResult,
+  TypedAddListener,
+  TypedCreateListenerEntry,
+  TypedRemoveListener,
+  UnsubscribeListener,
+  UnsubscribeListenerOptions,
+} from './types'
+import {
+  addAbortSignalListener,
+  assertFunction,
+  catchRejection,
+  noop,
+} from './utils'
+export { TaskAbortError } from './exceptions'
+export type {
+  AsyncTaskExecutor,
+  CreateListenerMiddlewareOptions,
+  ForkedTask,
+  ForkedTaskAPI,
+  ForkedTaskExecutor,
+  ListenerEffect,
+  ListenerEffectAPI,
+  ListenerErrorHandler,
+  ListenerMiddleware,
+  ListenerMiddlewareInstance,
+  SyncTaskExecutor,
+  TaskCancelled,
+  TaskRejected,
+  TaskResolved,
+  TaskResult,
+  TypedAddListener,
+  TypedRemoveListener,
+  TypedStartListening,
+  TypedStopListening,
+  UnsubscribeListener,
+  UnsubscribeListenerOptions,
+} from './types'
+
+//Overly-aggressive byte-shaving
+const { assign } = Object
+/**
+ * @internal
+ */
+const INTERNAL_NIL_TOKEN = {} as const
+
+const alm = 'listenerMiddleware' as const
+
+const createFork = (
+  parentAbortSignal: AbortSignal,
+  parentBlockingPromises: Promise<any>[],
+) => {
+  const linkControllers = (controller: AbortController) =>
+    addAbortSignalListener(parentAbortSignal, () =>
+      controller.abort(parentAbortSignal.reason),
+    )
+
+  return <T>(
+    taskExecutor: ForkedTaskExecutor<T>,
+    opts?: ForkOptions,
+  ): ForkedTask<T> => {
+    assertFunction(taskExecutor, 'taskExecutor')
+    const childAbortController = new AbortController()
+
+    linkControllers(childAbortController)
+
+    const result = runTask<T>(
+      async (): Promise<T> => {
+        validateActive(parentAbortSignal)
+        validateActive(childAbortController.signal)
+        const result = (await taskExecutor({
+          pause: createPause(childAbortController.signal),
+          delay: createDelay(childAbortController.signal),
+          signal: childAbortController.signal,
+        })) as T
+        validateActive(childAbortController.signal)
+        return result
+      },
+      () => childAbortController.abort(taskCompleted),
+    )
+
+    if (opts?.autoJoin) {
+      parentBlockingPromises.push(result.catch(noop))
+    }
+
+    return {
+      result: createPause<TaskResult<T>>(parentAbortSignal)(result),
+      cancel() {
+        childAbortController.abort(taskCancelled)
+      },
+    }
+  }
+}
+
+const createTakePattern = <S>(
+  startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>,
+  signal: AbortSignal,
+): TakePattern<S> => {
+  /**
+   * A function that takes a ListenerPredicate and an optional timeout,
+   * and resolves when either the predicate returns `true` based on an action
+   * state combination or when the timeout expires.
+   * If the parent listener is canceled while waiting, this will throw a
+   * TaskAbortError.
+   */
+  const take = async <P extends AnyListenerPredicate<S>>(
+    predicate: P,
+    timeout: number | undefined,
+  ) => {
+    validateActive(signal)
+
+    // Placeholder unsubscribe function until the listener is added
+    let unsubscribe: UnsubscribeListener = () => {}
+
+    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {
+      // Inside the Promise, we synchronously add the listener.
+      let stopListening = startListening({
+        predicate: predicate as any,
+        effect: (action, listenerApi): void => {
+          // One-shot listener that cleans up as soon as the predicate passes
+          listenerApi.unsubscribe()
+          // Resolve the promise with the same arguments the predicate saw
+          resolve([
+            action,
+            listenerApi.getState(),
+            listenerApi.getOriginalState(),
+          ])
+        },
+      })
+      unsubscribe = () => {
+        stopListening()
+        reject()
+      }
+    })
+
+    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise]
+
+    if (timeout != null) {
+      promises.push(
+        new Promise<null>((resolve) => setTimeout(resolve, timeout, null)),
+      )
+    }
+
+    try {
+      const output = await raceWithSignal(signal, Promise.race(promises))
+
+      validateActive(signal)
+      return output
+    } finally {
+      // Always clean up the listener
+      unsubscribe()
+    }
+  }
+
+  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) =>
+    catchRejection(take(predicate, timeout))) as TakePattern<S>
+}
+
+const getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {
+  let { type, actionCreator, matcher, predicate, effect } = options
+
+  if (type) {
+    predicate = createAction(type).match
+  } else if (actionCreator) {
+    type = actionCreator!.type
+    predicate = actionCreator.match
+  } else if (matcher) {
+    predicate = matcher
+  } else if (predicate) {
+    // pass
+  } else {
+    throw new Error(
+      'Creating or removing a listener requires one of the known fields for matching an action',
+    )
+  }
+
+  assertFunction(effect, 'options.listener')
+
+  return { predicate, type, effect }
+}
+
+/** Accepts the possible options for creating a listener, and returns a formatted listener entry */
+export const createListenerEntry: TypedCreateListenerEntry<unknown> =
+  /* @__PURE__ */ assign(
+    (options: FallbackAddListenerOptions) => {
+      const { type, predicate, effect } = getListenerEntryPropsFrom(options)
+
+      const entry: ListenerEntry<unknown> = {
+        id: nanoid(),
+        effect,
+        type,
+        predicate,
+        pending: new Set<AbortController>(),
+        unsubscribe: () => {
+          throw new Error('Unsubscribe not initialized')
+        },
+      }
+
+      return entry
+    },
+    { withTypes: () => createListenerEntry },
+  ) as unknown as TypedCreateListenerEntry<unknown>
+
+const findListenerEntry = (
+  listenerMap: Map<string, ListenerEntry>,
+  options: FallbackAddListenerOptions,
+) => {
+  const { type, effect, predicate } = getListenerEntryPropsFrom(options)
+
+  return Array.from(listenerMap.values()).find((entry) => {
+    const matchPredicateOrType =
+      typeof type === 'string'
+        ? entry.type === type
+        : entry.predicate === predicate
+
+    return matchPredicateOrType && entry.effect === effect
+  })
+}
+
+const cancelActiveListeners = (
+  entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
+) => {
+  entry.pending.forEach((controller) => {
+    controller.abort(listenerCancelled)
+  })
+}
+
+const createClearListenerMiddleware = (
+  listenerMap: Map<string, ListenerEntry>,
+  executingListeners: Map<ListenerEntry, number>,
+) => {
+  return () => {
+    for (const listener of executingListeners.keys()) {
+      cancelActiveListeners(listener)
+    }
+    listenerMap.clear()
+  }
+}
+
+/**
+ * Safely reports errors to the `errorHandler` provided.
+ * Errors that occur inside `errorHandler` are notified in a new task.
+ * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)
+ * @param errorHandler
+ * @param errorToNotify
+ */
+const safelyNotifyError = (
+  errorHandler: ListenerErrorHandler,
+  errorToNotify: unknown,
+  errorInfo: ListenerErrorInfo,
+): void => {
+  try {
+    errorHandler(errorToNotify, errorInfo)
+  } catch (errorHandlerError) {
+    // We cannot let an error raised here block the listener queue.
+    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...
+    setTimeout(() => {
+      throw errorHandlerError
+    }, 0)
+  }
+}
+
+/**
+ * @public
+ */
+export const addListener = /* @__PURE__ */ assign(
+  /* @__PURE__ */ createAction(`${alm}/add`),
+  {
+    withTypes: () => addListener,
+  },
+) as unknown as TypedAddListener<unknown>
+
+/**
+ * @public
+ */
+export const clearAllListeners = /* @__PURE__ */ createAction(
+  `${alm}/removeAll`,
+)
+
+/**
+ * @public
+ */
+export const removeListener = /* @__PURE__ */ assign(
+  /* @__PURE__ */ createAction(`${alm}/remove`),
+  {
+    withTypes: () => removeListener,
+  },
+) as unknown as TypedRemoveListener<unknown>
+
+const defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {
+  console.error(`${alm}/error`, ...args)
+}
+
+/**
+ * @public
+ */
+export const createListenerMiddleware = <
+  StateType = unknown,
+  DispatchType extends Dispatch<Action> = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+>(
+  middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},
+) => {
+  const listenerMap = new Map<string, ListenerEntry>()
+
+  // Track listeners whose effect is currently executing so clearListeners can
+  // abort even listeners that have become unsubscribed while executing.
+  const executingListeners = new Map<ListenerEntry, number>()
+  const trackExecutingListener = (entry: ListenerEntry) => {
+    const count = executingListeners.get(entry) ?? 0
+    executingListeners.set(entry, count + 1)
+  }
+  const untrackExecutingListener = (entry: ListenerEntry) => {
+    const count = executingListeners.get(entry) ?? 1
+    if (count === 1) {
+      executingListeners.delete(entry)
+    } else {
+      executingListeners.set(entry, count - 1)
+    }
+  }
+
+  const { extra, onError = defaultErrorHandler } = middlewareOptions
+
+  assertFunction(onError, 'onError')
+
+  const insertEntry = (entry: ListenerEntry) => {
+    entry.unsubscribe = () => listenerMap.delete(entry.id)
+
+    listenerMap.set(entry.id, entry)
+    return (cancelOptions?: UnsubscribeListenerOptions) => {
+      entry.unsubscribe()
+      if (cancelOptions?.cancelActive) {
+        cancelActiveListeners(entry)
+      }
+    }
+  }
+
+  const startListening = ((options: FallbackAddListenerOptions) => {
+    const entry =
+      findListenerEntry(listenerMap, options) ??
+      createListenerEntry(options as any)
+
+    return insertEntry(entry)
+  }) as AddListenerOverloads<any>
+
+  assign(startListening, {
+    withTypes: () => startListening,
+  })
+
+  const stopListening = (
+    options: FallbackAddListenerOptions & UnsubscribeListenerOptions,
+  ): boolean => {
+    const entry = findListenerEntry(listenerMap, options)
+
+    if (entry) {
+      entry.unsubscribe()
+      if (options.cancelActive) {
+        cancelActiveListeners(entry)
+      }
+    }
+
+    return !!entry
+  }
+
+  assign(stopListening, {
+    withTypes: () => stopListening,
+  })
+
+  const notifyListener = async (
+    entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
+    action: unknown,
+    api: MiddlewareAPI,
+    getOriginalState: () => StateType,
+  ) => {
+    const internalTaskController = new AbortController()
+    const take = createTakePattern(
+      startListening as AddListenerOverloads<any>,
+      internalTaskController.signal,
+    )
+    const autoJoinPromises: Promise<any>[] = []
+
+    try {
+      entry.pending.add(internalTaskController)
+      trackExecutingListener(entry)
+      await Promise.resolve(
+        entry.effect(
+          action,
+          // Use assign() rather than ... to avoid extra helper functions added to bundle
+          assign({}, api, {
+            getOriginalState,
+            condition: (
+              predicate: AnyListenerPredicate<any>,
+              timeout?: number,
+            ) => take(predicate, timeout).then(Boolean),
+            take,
+            delay: createDelay(internalTaskController.signal),
+            pause: createPause<any>(internalTaskController.signal),
+            extra,
+            signal: internalTaskController.signal,
+            fork: createFork(internalTaskController.signal, autoJoinPromises),
+            unsubscribe: entry.unsubscribe,
+            subscribe: () => {
+              listenerMap.set(entry.id, entry)
+            },
+            cancelActiveListeners: () => {
+              entry.pending.forEach((controller, _, set) => {
+                if (controller !== internalTaskController) {
+                  controller.abort(listenerCancelled)
+                  set.delete(controller)
+                }
+              })
+            },
+            cancel: () => {
+              internalTaskController.abort(listenerCancelled)
+              entry.pending.delete(internalTaskController)
+            },
+            throwIfCancelled: () => {
+              validateActive(internalTaskController.signal)
+            },
+          }),
+        ),
+      )
+    } catch (listenerError) {
+      if (!(listenerError instanceof TaskAbortError)) {
+        safelyNotifyError(onError, listenerError, {
+          raisedBy: 'effect',
+        })
+      }
+    } finally {
+      await Promise.all(autoJoinPromises)
+
+      internalTaskController.abort(listenerCompleted) // Notify that the task has completed
+      untrackExecutingListener(entry)
+      entry.pending.delete(internalTaskController)
+    }
+  }
+
+  const clearListenerMiddleware = createClearListenerMiddleware(
+    listenerMap,
+    executingListeners,
+  )
+
+  const middleware: ListenerMiddleware<
+    StateType,
+    DispatchType,
+    ExtraArgument
+  > = (api) => (next) => (action) => {
+    if (!isAction(action)) {
+      // we only want to notify listeners for action objects
+      return next(action)
+    }
+
+    if (addListener.match(action)) {
+      return startListening(action.payload as any)
+    }
+
+    if (clearAllListeners.match(action)) {
+      clearListenerMiddleware()
+      return
+    }
+
+    if (removeListener.match(action)) {
+      return stopListening(action.payload)
+    }
+
+    // Need to get this state _before_ the reducer processes the action
+    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState()
+
+    // `getOriginalState` can only be called synchronously.
+    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820
+    const getOriginalState = (): StateType => {
+      if (originalState === INTERNAL_NIL_TOKEN) {
+        throw new Error(
+          `${alm}: getOriginalState can only be called synchronously`,
+        )
+      }
+
+      return originalState as StateType
+    }
+
+    let result: unknown
+
+    try {
+      // Actually forward the action to the reducer before we handle listeners
+      result = next(action)
+
+      if (listenerMap.size > 0) {
+        const currentState = api.getState()
+        // Work around ESBuild+TS transpilation issue
+        const listenerEntries = Array.from(listenerMap.values())
+        for (const entry of listenerEntries) {
+          let runListener = false
+
+          try {
+            runListener = entry.predicate(action, currentState, originalState)
+          } catch (predicateError) {
+            runListener = false
+
+            safelyNotifyError(onError, predicateError, {
+              raisedBy: 'predicate',
+            })
+          }
+
+          if (!runListener) {
+            continue
+          }
+
+          notifyListener(entry, action, api, getOriginalState)
+        }
+      }
+    } finally {
+      // Remove `originalState` store from this scope.
+      originalState = INTERNAL_NIL_TOKEN
+    }
+
+    return result
+  }
+
+  return {
+    middleware,
+    startListening,
+    stopListening,
+    clearListeners: clearListenerMiddleware,
+  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>
+}
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/task.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,100 @@
+import { TaskAbortError } from './exceptions'
+import type { TaskResult } from './types'
+import { addAbortSignalListener, catchRejection, noop } from './utils'
+
+/**
+ * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.
+ * @param signal
+ * @see {TaskAbortError}
+ * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.
+ */
+export const validateActive = (signal: AbortSignal): void => {
+  if (signal.aborted) {
+    throw new TaskAbortError(signal.reason)
+  }
+}
+
+/**
+ * Generates a race between the promise(s) and the AbortSignal
+ * This avoids `Promise.race()`-related memory leaks:
+ * https://github.com/nodejs/node/issues/17469#issuecomment-349794909
+ */
+export function raceWithSignal<T>(
+  signal: AbortSignal,
+  promise: Promise<T>,
+): Promise<T> {
+  let cleanup = noop
+  return new Promise<T>((resolve, reject) => {
+    const notifyRejection = () => reject(new TaskAbortError(signal.reason))
+
+    if (signal.aborted) {
+      notifyRejection()
+      return
+    }
+
+    cleanup = addAbortSignalListener(signal, notifyRejection)
+    promise.finally(() => cleanup()).then(resolve, reject)
+  }).finally(() => {
+    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more
+    cleanup = noop
+  })
+}
+
+/**
+ * Runs a task and returns promise that resolves to {@link TaskResult}.
+ * Second argument is an optional `cleanUp` function that always runs after task.
+ *
+ * **Note:** `runTask` runs the executor in the next microtask.
+ * @returns
+ */
+export const runTask = async <T>(
+  task: () => Promise<T>,
+  cleanUp?: () => void,
+): Promise<TaskResult<T>> => {
+  try {
+    await Promise.resolve()
+    const value = await task()
+    return {
+      status: 'ok',
+      value,
+    }
+  } catch (error: any) {
+    return {
+      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',
+      error,
+    }
+  } finally {
+    cleanUp?.()
+  }
+}
+
+/**
+ * Given an input `AbortSignal` and a promise returns another promise that resolves
+ * as soon the input promise is provided or rejects as soon as
+ * `AbortSignal.abort` is `true`.
+ * @param signal
+ * @returns
+ */
+export const createPause = <T>(signal: AbortSignal) => {
+  return (promise: Promise<T>): Promise<T> => {
+    return catchRejection(
+      raceWithSignal(signal, promise).then((output) => {
+        validateActive(signal)
+        return output
+      }),
+    )
+  }
+}
+
+/**
+ * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves
+ * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.
+ * @param signal
+ * @returns
+ */
+export const createDelay = (signal: AbortSignal) => {
+  const pause = createPause<void>(signal)
+  return (timeoutMs: number): Promise<void> => {
+    return pause(new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)))
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,498 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAction,
+  createListenerMiddleware,
+  createSlice,
+  isAnyOf,
+  TaskAbortError,
+} from '@reduxjs/toolkit'
+
+describe('Saga-style Effects Scenarios', () => {
+  interface CounterState {
+    value: number
+  }
+
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: { value: 0 } as CounterState,
+    reducers: {
+      increment(state) {
+        state.value += 1
+      },
+      decrement(state) {
+        state.value -= 1
+      },
+      // Use the PayloadAction type to declare the contents of `action.payload`
+      incrementByAmount: (state, action: PayloadAction<number>) => {
+        state.value += action.payload
+      },
+    },
+  })
+  const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+  let { reducer } = counterSlice
+  let listenerMiddleware = createListenerMiddleware<CounterState>()
+  let { middleware, startListening, stopListening } = listenerMiddleware
+
+  let store = configureStore({
+    reducer,
+    middleware: (gDM) => gDM().prepend(middleware),
+  })
+
+  const testAction1 = createAction<string>('testAction1')
+  type TestAction1 = ReturnType<typeof testAction1>
+  const testAction2 = createAction<string>('testAction2')
+  type TestAction2 = ReturnType<typeof testAction2>
+  const testAction3 = createAction<string>('testAction3')
+  type TestAction3 = ReturnType<typeof testAction3>
+
+  type RootState = ReturnType<typeof store.getState>
+
+  function delay(ms: number) {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+  }
+
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware<CounterState>()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    store = configureStore({
+      reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  afterEach(() => {
+    vi.clearAllMocks()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+  })
+
+  test('throttle', async () => {
+    // Ignore incoming actions for a given period of time while processing a task.
+    // Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args
+
+    let listenerCalls = 0
+    let workPerformed = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: (action, listenerApi) => {
+        listenerCalls++
+
+        // Stop listening until further notice
+        listenerApi.unsubscribe()
+
+        // Queue to start listening again after a delay
+        setTimeout(listenerApi.subscribe, 15)
+        workPerformed++
+      },
+    })
+
+    // Dispatch 3 actions. First triggers listener, next two ignored.
+    store.dispatch(increment())
+    store.dispatch(increment())
+    store.dispatch(increment())
+
+    // Wait for resubscription
+    await delay(25)
+
+    // Dispatch 2 more actions, first triggers, second ignored
+    store.dispatch(increment())
+    store.dispatch(increment())
+
+    // Wait for work
+    await delay(5)
+
+    // Both listener calls completed
+    expect(listenerCalls).toBe(2)
+    expect(workPerformed).toBe(2)
+  })
+
+  test('debounce / takeLatest', async () => {
+    // Repeated calls cancel previous ones, no work performed
+    // until the specified delay elapses without another call
+    // NOTE: This is also basically identical to `takeLatest`.
+    // Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args
+    // Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args
+
+    let listenerCalls = 0
+    let workPerformed = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        listenerCalls++
+
+        // Cancel any in-progress instances of this listener
+        listenerApi.cancelActiveListeners()
+
+        // Delay before starting actual work
+        await listenerApi.delay(15)
+
+        workPerformed++
+      },
+    })
+
+    // First action, listener 1 starts, nothing to cancel
+    store.dispatch(increment())
+    // Second action, listener 2 starts, cancels 1
+    store.dispatch(increment())
+    // Third action, listener 3 starts, cancels 2
+    store.dispatch(increment())
+
+    // 3 listeners started, third is still paused
+    expect(listenerCalls).toBe(3)
+    expect(workPerformed).toBe(0)
+
+    await delay(25)
+
+    // All 3 started
+    expect(listenerCalls).toBe(3)
+    // First two canceled, `delay()` threw JobCanceled and skipped work.
+    // Third actually completed.
+    expect(workPerformed).toBe(1)
+  })
+
+  test('takeEvery', async () => {
+    // Runs the listener on every action match
+    // Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args
+
+    // NOTE: This is already the default behavior - nothing special here!
+
+    let listenerCalls = 0
+    startListening({
+      actionCreator: increment,
+      effect: (action, listenerApi) => {
+        listenerCalls++
+      },
+    })
+
+    store.dispatch(increment())
+    expect(listenerCalls).toBe(1)
+
+    store.dispatch(increment())
+    expect(listenerCalls).toBe(2)
+  })
+
+  test('takeLeading', async () => {
+    // Starts listener on first action, ignores others until task completes
+    // Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args
+
+    let listenerCalls = 0
+    let workPerformed = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        listenerCalls++
+
+        // Stop listening for this action
+        listenerApi.unsubscribe()
+
+        // Pretend we're doing expensive work
+        await listenerApi.delay(25)
+
+        workPerformed++
+
+        // Re-enable the listener
+        listenerApi.subscribe()
+      },
+    })
+
+    // First action starts the listener, which unsubscribes
+    store.dispatch(increment())
+    // Second action is ignored
+    store.dispatch(increment())
+
+    // One instance in progress, but not complete
+    expect(listenerCalls).toBe(1)
+    expect(workPerformed).toBe(0)
+
+    await delay(5)
+
+    // In-progress listener not done yet
+    store.dispatch(increment())
+
+    // No changes in status
+    expect(listenerCalls).toBe(1)
+    expect(workPerformed).toBe(0)
+
+    await delay(50)
+
+    // Work finished, should have resubscribed
+    expect(workPerformed).toBe(1)
+
+    // Listener is re-subscribed, will trigger again
+    store.dispatch(increment())
+
+    expect(listenerCalls).toBe(2)
+    expect(workPerformed).toBe(1)
+
+    await delay(50)
+
+    expect(workPerformed).toBe(2)
+  })
+
+  test('fork + join', async () => {
+    // fork starts a child job, join waits for the child to complete and return a value
+    // Ref: https://redux-saga.js.org/docs/api#forkfn-args
+    // Ref: https://redux-saga.js.org/docs/api#jointask
+
+    let childResult = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        const childOutput = 42
+        // Spawn a child job and start it immediately
+        const result = await listenerApi.fork(async () => {
+          // Artificially wait a bit inside the child
+          await listenerApi.delay(5)
+          // Complete the child by returning an Outcome-wrapped value
+          return childOutput
+        }).result
+
+        // Unwrap the child result in the listener
+        if (result.status === 'ok') {
+          childResult = result.value
+        }
+      },
+    })
+
+    store.dispatch(increment())
+
+    await delay(10)
+    expect(childResult).toBe(42)
+  })
+
+  test('fork + cancel', async () => {
+    // fork starts a child job, cancel will raise an exception if the
+    // child is paused in the middle of an effect
+    // Ref: https://redux-saga.js.org/docs/api#forkfn-args
+
+    let childResult = 0
+    let listenerCompleted = false
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        // Spawn a child job and start it immediately
+        const forkedTask = listenerApi.fork(async () => {
+          // Artificially wait a bit inside the child
+          await listenerApi.delay(15)
+          // Complete the child by returning an Outcome-wrapped value
+          childResult = 42
+
+          return 0
+        })
+
+        await listenerApi.delay(5)
+        forkedTask.cancel()
+        listenerCompleted = true
+      },
+    })
+
+    // Starts listener, which starts child
+    store.dispatch(increment())
+
+    // Wait for child to have maybe completed
+    await delay(20)
+
+    // Listener finished, but the child was canceled and threw an exception, so it never finished
+    expect(listenerCompleted).toBe(true)
+    expect(childResult).toBe(0)
+  })
+
+  test('canceled', async () => {
+    // canceled allows checking if the current task was canceled
+    // Ref: https://redux-saga.js.org/docs/api#cancelled
+
+    let canceledAndCaught = false
+    let canceledCheck = false
+
+    startListening({
+      matcher: isAnyOf(increment, decrement, incrementByAmount),
+      effect: async (action, listenerApi) => {
+        if (increment.match(action)) {
+          // Have this branch wait around to be canceled by the other
+          try {
+            await listenerApi.delay(10)
+          } catch (err) {
+            // Can check cancelation based on the exception and its reason
+            if (err instanceof TaskAbortError) {
+              canceledAndCaught = true
+            }
+          }
+        } else if (incrementByAmount.match(action)) {
+          // do a non-cancelation-aware wait
+          await delay(15)
+          if (listenerApi.signal.aborted) {
+            canceledCheck = true
+          }
+        } else if (decrement.match(action)) {
+          listenerApi.cancelActiveListeners()
+        }
+      },
+    })
+
+    // Start first branch
+    store.dispatch(increment())
+    // Cancel first listener
+    store.dispatch(decrement())
+
+    // Have to wait for the delay to resolve
+    // TODO Can we make ``Job.delay()` be a race?
+    await delay(15)
+
+    expect(canceledAndCaught).toBe(true)
+
+    // Start second branch
+    store.dispatch(incrementByAmount(42))
+    // Cancel second listener, although it won't know about that until later
+    store.dispatch(decrement())
+
+    expect(canceledCheck).toBe(false)
+
+    await delay(20)
+
+    expect(canceledCheck).toBe(true)
+  })
+
+  test('long-running listener with immediate unsubscribe is cancelable', async () => {
+    let runCount = 0
+    let abortCount = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        runCount++
+
+        // Stop listening for this action
+        listenerApi.unsubscribe()
+
+        try {
+          // Wait indefinitely
+          await listenerApi.condition(() => false)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            abortCount++
+          }
+        }
+      },
+    })
+
+    // First action starts the listener, which unsubscribes
+    store.dispatch(increment())
+    expect(runCount).toBe(1)
+
+    // Verify that the first action unsubscribed the listener
+    store.dispatch(increment())
+    expect(runCount).toBe(1)
+
+    // Now call clearListeners, which should abort the running effect, even
+    // though the listener is no longer subscribed
+    listenerMiddleware.clearListeners()
+    await delay(0)
+
+    expect(abortCount).toBe(1)
+  })
+
+  test('long-running listener with unsubscribe race is cancelable', async () => {
+    let runCount = 0
+    let abortCount = 0
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        runCount++
+
+        if (runCount === 2) {
+          // On the second run, stop listening for this action
+          listenerApi.unsubscribe()
+          return
+        }
+
+        try {
+          // Wait indefinitely
+          await listenerApi.condition(() => false)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            abortCount++
+          }
+        }
+      },
+    })
+
+    // First action starts the hanging effect
+    store.dispatch(increment())
+    expect(runCount).toBe(1)
+
+    // Second action starts the fast effect, which unsubscribes
+    store.dispatch(increment())
+    expect(runCount).toBe(2)
+
+    // Third action should be a noop
+    store.dispatch(increment())
+    expect(runCount).toBe(2)
+
+    // The hanging effect should still be hanging
+    expect(abortCount).toBe(0)
+
+    // Now call clearListeners, which should abort the hanging effect, even
+    // though the listener is no longer subscribed
+    listenerMiddleware.clearListeners()
+    await delay(0)
+
+    expect(abortCount).toBe(1)
+  })
+
+  test('long-running listener with immediate unsubscribe and forked child is cancelable', async () => {
+    let outerAborted = false
+    let innerAborted = false
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        // Stop listening for this action
+        listenerApi.unsubscribe()
+
+        const pollingTask = listenerApi.fork(async (forkApi) => {
+          try {
+            // Cancellation-aware indefinite pause
+            await forkApi.pause(new Promise(() => {}))
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              innerAborted = true
+            }
+          }
+        })
+
+        try {
+          // Wait indefinitely
+          await listenerApi.condition(() => false)
+          pollingTask.cancel()
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            outerAborted = true
+          }
+        }
+      },
+    })
+
+    store.dispatch(increment())
+    await delay(0)
+
+    listenerMiddleware.clearListeners()
+    await delay(0)
+
+    expect(outerAborted).toBe(true)
+    expect(innerAborted).toBe(true)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/fork.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/fork.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/fork.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,524 @@
+import type { EnhancedStore } from '@reduxjs/toolkit'
+import { configureStore, createSlice, createAction } from '@reduxjs/toolkit'
+
+import type { PayloadAction } from '@reduxjs/toolkit'
+import type { ForkedTaskExecutor, TaskResult } from '../types'
+import { createListenerMiddleware, TaskAbortError } from '../index'
+import {
+  listenerCancelled,
+  listenerCompleted,
+  taskCancelled,
+  taskCompleted,
+} from '../exceptions'
+
+function delay(ms: number) {
+  return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+// @see https://deno.land/std@0.95.0/async/deferred.ts (MIT)
+export interface Deferred<T> extends Promise<T> {
+  resolve(value?: T | PromiseLike<T>): void
+  reject(reason?: any): void
+}
+
+/** Creates a Promise with the `reject` and `resolve` functions
+ * placed as methods on the promise object itself. It allows you to do:
+ *
+ *     const p = deferred<number>();
+ *     // ...
+ *     p.resolve(42);
+ */
+export function deferred<T>(): Deferred<T> {
+  let methods
+  const promise = new Promise<T>((resolve, reject): void => {
+    methods = { resolve, reject }
+  })
+  return Object.assign(promise, methods) as Deferred<T>
+}
+
+interface CounterSlice {
+  value: number
+}
+
+describe('fork', () => {
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: { value: 0 } as CounterSlice,
+    reducers: {
+      increment(state) {
+        state.value += 1
+      },
+      decrement(state) {
+        state.value -= 1
+      },
+      // Use the PayloadAction type to declare the contents of `action.payload`
+      incrementByAmount: (state, action: PayloadAction<number>) => {
+        state.value += action.payload
+      },
+    },
+  })
+  const { increment, decrement, incrementByAmount } = counterSlice.actions
+  let listenerMiddleware = createListenerMiddleware()
+  let { middleware, startListening, stopListening } = listenerMiddleware
+  let store = configureStore({
+    reducer: counterSlice.reducer,
+    middleware: (gDM) => gDM().prepend(middleware),
+  })
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    stopListening = listenerMiddleware.stopListening
+    store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  it('runs executors in the next microtask', async () => {
+    let hasRunSyncExector = false
+    let hasRunAsyncExecutor = false
+
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        listenerApi.fork(() => {
+          hasRunSyncExector = true
+        })
+
+        listenerApi.fork(async () => {
+          hasRunAsyncExecutor = true
+        })
+      },
+    })
+
+    store.dispatch(increment())
+
+    expect(hasRunSyncExector).toBe(false)
+    expect(hasRunAsyncExecutor).toBe(false)
+
+    await Promise.resolve()
+
+    expect(hasRunSyncExector).toBe(true)
+    expect(hasRunAsyncExecutor).toBe(true)
+  })
+
+  test('forkedTask.result rejects TaskAbortError if listener is cancelled', async () => {
+    const deferredForkedTaskError = deferred()
+
+    startListening({
+      actionCreator: increment,
+      async effect(_, listenerApi) {
+        listenerApi.cancelActiveListeners()
+        listenerApi
+          .fork(async () => {
+            await delay(10)
+
+            throw new Error('unreachable code')
+          })
+          .result.then(
+            deferredForkedTaskError.resolve,
+            deferredForkedTaskError.resolve,
+          )
+      },
+    })
+
+    store.dispatch(increment())
+    store.dispatch(increment())
+
+    expect(await deferredForkedTaskError).toEqual(
+      new TaskAbortError(listenerCancelled),
+    )
+  })
+
+  it('synchronously throws TypeError error if the provided executor is not a function', () => {
+    const invalidExecutors = [null, {}, undefined, 1]
+
+    startListening({
+      predicate: () => true,
+      effect: async (_, listenerApi) => {
+        invalidExecutors.forEach((invalidExecutor) => {
+          let caughtError
+          try {
+            listenerApi.fork(invalidExecutor as any)
+          } catch (err) {
+            caughtError = err
+          }
+
+          expect(caughtError).toBeInstanceOf(TypeError)
+        })
+      },
+    })
+
+    store.dispatch(increment())
+
+    expect.assertions(invalidExecutors.length)
+  })
+
+  it('does not run an executor if the task is synchronously cancelled', async () => {
+    const storeStateAfter = deferred()
+
+    startListening({
+      actionCreator: increment,
+      effect: async (action, listenerApi) => {
+        const forkedTask = listenerApi.fork(() => {
+          listenerApi.dispatch(decrement())
+          listenerApi.dispatch(decrement())
+          listenerApi.dispatch(decrement())
+        })
+        forkedTask.cancel()
+
+        const result = await forkedTask.result
+        storeStateAfter.resolve(listenerApi.getState())
+      },
+    })
+    store.dispatch(increment())
+
+    await expect(storeStateAfter).resolves.toEqual({ value: 1 })
+  })
+
+  it.each<{
+    desc: string
+    executor: ForkedTaskExecutor<any>
+    cancelAfterMs?: number
+    expected: TaskResult<any>
+  }>([
+    {
+      desc: 'sync exec - success',
+      executor: () => 42,
+      expected: { status: 'ok', value: 42 },
+    },
+    {
+      desc: 'sync exec - error',
+      executor: () => {
+        throw new Error('2020')
+      },
+      expected: { status: 'rejected', error: new Error('2020') },
+    },
+    {
+      desc: 'sync exec - sync cancel',
+      executor: () => 42,
+      cancelAfterMs: -1,
+      expected: {
+        status: 'cancelled',
+        error: new TaskAbortError(taskCancelled),
+      },
+    },
+    {
+      desc: 'sync exec - async cancel',
+      executor: () => 42,
+      cancelAfterMs: 0,
+      expected: { status: 'ok', value: 42 },
+    },
+    {
+      desc: 'async exec - async cancel',
+      executor: async (forkApi) => {
+        await forkApi.delay(100)
+        throw new Error('2020')
+      },
+      cancelAfterMs: 10,
+      expected: {
+        status: 'cancelled',
+        error: new TaskAbortError(taskCancelled),
+      },
+    },
+    {
+      desc: 'async exec - success',
+      executor: async () => {
+        await delay(20)
+        return Promise.resolve(21)
+      },
+      expected: { status: 'ok', value: 21 },
+    },
+    {
+      desc: 'async exec - error',
+      executor: async () => {
+        await Promise.resolve()
+        throw new Error('2020')
+      },
+      expected: { status: 'rejected', error: new Error('2020') },
+    },
+    {
+      desc: 'async exec - success with forkApi.pause',
+      executor: async (forkApi) => {
+        return forkApi.pause(Promise.resolve(2))
+      },
+      expected: { status: 'ok', value: 2 },
+    },
+    {
+      desc: 'async exec - error with forkApi.pause',
+      executor: async (forkApi) => {
+        return forkApi.pause(Promise.reject(22))
+      },
+      expected: { status: 'rejected', error: 22 },
+    },
+    {
+      desc: 'async exec - success with forkApi.delay',
+      executor: async (forkApi) => {
+        await forkApi.delay(10)
+        return 5
+      },
+      expected: { status: 'ok', value: 5 },
+    },
+  ])('$desc', async ({ executor, expected, cancelAfterMs }) => {
+    let deferredResult = deferred()
+    let forkedTask: any = {}
+
+    startListening({
+      predicate: () => true,
+      effect: async (_, listenerApi) => {
+        forkedTask = listenerApi.fork(executor)
+
+        deferredResult.resolve(await forkedTask.result)
+      },
+    })
+
+    store.dispatch({ type: '' })
+
+    if (typeof cancelAfterMs === 'number') {
+      if (cancelAfterMs < 0) {
+        forkedTask.cancel()
+      } else {
+        await delay(cancelAfterMs)
+        forkedTask.cancel()
+      }
+    }
+
+    const result = await deferredResult
+
+    expect(result).toEqual(expected)
+  })
+
+  describe('forkAPI', () => {
+    test('forkApi.delay rejects as soon as the task is cancelled', async () => {
+      let deferredResult = deferred()
+
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          const forkedTask = listenerApi.fork(async (forkApi) => {
+            await forkApi.delay(100)
+
+            return 4
+          })
+
+          await listenerApi.delay(10)
+          forkedTask.cancel()
+          deferredResult.resolve(await forkedTask.result)
+        },
+      })
+
+      store.dispatch(increment())
+
+      expect(await deferredResult).toEqual({
+        status: 'cancelled',
+        error: new TaskAbortError(taskCancelled),
+      })
+    })
+
+    test('forkApi.delay rejects as soon as the parent listener is cancelled', async () => {
+      let deferredResult = deferred()
+
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          listenerApi.cancelActiveListeners()
+          await listenerApi.fork(async (forkApi) => {
+            await forkApi
+              .delay(100)
+              .then(deferredResult.resolve, deferredResult.resolve)
+
+            return 4
+          }).result
+
+          deferredResult.resolve(new Error('unreachable'))
+        },
+      })
+
+      store.dispatch(increment())
+
+      await Promise.resolve()
+
+      store.dispatch(increment())
+      expect(await deferredResult).toEqual(
+        new TaskAbortError(listenerCancelled),
+      )
+    })
+
+    it.each([
+      {
+        autoJoin: true,
+        expectedAbortReason: taskCompleted,
+        cancelListener: false,
+      },
+      {
+        autoJoin: false,
+        expectedAbortReason: listenerCompleted,
+        cancelListener: false,
+      },
+      {
+        autoJoin: true,
+        expectedAbortReason: listenerCancelled,
+        cancelListener: true,
+      },
+      {
+        autoJoin: false,
+        expectedAbortReason: listenerCancelled,
+        cancelListener: true,
+      },
+    ])(
+      'signal is $expectedAbortReason when autoJoin: $autoJoin, cancelListener: $cancelListener',
+      async ({ autoJoin, cancelListener, expectedAbortReason }) => {
+        let deferredResult = deferred()
+
+        const unsubscribe = startListening({
+          actionCreator: increment,
+          async effect(_, listenerApi) {
+            listenerApi.fork(
+              async (forkApi) => {
+                forkApi.signal.addEventListener('abort', () => {
+                  deferredResult.resolve(forkApi.signal.reason)
+                })
+
+                await forkApi.delay(10)
+              },
+              { autoJoin },
+            )
+          },
+        })
+
+        store.dispatch(increment())
+
+        // let task start
+        await Promise.resolve()
+
+        if (cancelListener) unsubscribe({ cancelActive: true })
+
+        expect(await deferredResult).toBe(expectedAbortReason)
+      },
+    )
+
+    test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => {
+      let deferredCompletedEvt = deferred()
+      let deferredCancelledEvt = deferred()
+
+      // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620
+      // This test just fails if an `unhandledRejection` occurs.
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          const completedTask = listenerApi.fork(async (forkApi) => {
+            forkApi.signal.addEventListener(
+              'abort',
+              deferredCompletedEvt.resolve,
+              { once: true },
+            )
+            forkApi.delay(100) // missing await
+
+            return 4
+          })
+
+          deferredCompletedEvt.resolve(await completedTask.result)
+
+          const godotPauseTrigger = deferred()
+
+          const cancelledTask = listenerApi.fork(async (forkApi) => {
+            forkApi.signal.addEventListener(
+              'abort',
+              deferredCompletedEvt.resolve,
+              { once: true },
+            )
+            forkApi.delay(1_000) // missing await
+            await forkApi.pause(godotPauseTrigger)
+            return 4
+          })
+
+          await Promise.resolve()
+          cancelledTask.cancel()
+          deferredCancelledEvt.resolve(await cancelledTask.result)
+        },
+      })
+
+      store.dispatch(increment())
+      expect(await deferredCompletedEvt).toBeDefined()
+      expect(await deferredCancelledEvt).toBeDefined()
+    })
+  })
+
+  test('forkApi.pause rejects if task is cancelled', async () => {
+    let deferredResult = deferred()
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        const forkedTask = listenerApi.fork(async (forkApi) => {
+          await forkApi.pause(delay(1_000))
+
+          return 4
+        })
+
+        await Promise.resolve()
+        forkedTask.cancel()
+        deferredResult.resolve(await forkedTask.result)
+      },
+    })
+
+    store.dispatch(increment())
+
+    expect(await deferredResult).toEqual({
+      status: 'cancelled',
+      error: new TaskAbortError(taskCancelled),
+    })
+  })
+
+  test('forkApi.pause rejects as soon as the parent listener is cancelled', async () => {
+    let deferredResult = deferred()
+
+    startListening({
+      actionCreator: increment,
+      effect: async (_, listenerApi) => {
+        listenerApi.cancelActiveListeners()
+        const forkedTask = listenerApi.fork(async (forkApi) => {
+          await forkApi
+            .pause(delay(100))
+            .then(deferredResult.resolve, deferredResult.resolve)
+
+          return 4
+        })
+
+        await forkedTask.result
+        deferredResult.resolve(new Error('unreachable'))
+      },
+    })
+
+    store.dispatch(increment())
+
+    await Promise.resolve()
+
+    store.dispatch(increment())
+    expect(await deferredResult).toEqual(new TaskAbortError(listenerCancelled))
+  })
+
+  test('forkApi.pause rejects if listener is cancelled', async () => {
+    const incrementByInListener = createAction<number>('incrementByInListener')
+
+    startListening({
+      actionCreator: incrementByInListener,
+      async effect({ payload: amountToIncrement }, listenerApi) {
+        listenerApi.cancelActiveListeners()
+        await listenerApi.fork(async (forkApi) => {
+          await forkApi.pause(delay(10))
+          listenerApi.dispatch(incrementByAmount(amountToIncrement))
+        }).result
+        listenerApi.dispatch(incrementByAmount(2 * amountToIncrement))
+      },
+    })
+
+    store.dispatch(incrementByInListener(10))
+    store.dispatch(incrementByInListener(100))
+
+    await delay(50)
+
+    expect(store.getState().value).toEqual(300)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,540 @@
+import { createListenerEntry } from '@internal/listenerMiddleware'
+import type {
+  Action,
+  PayloadAction,
+  TypedAddListener,
+  TypedStartListening,
+  UnknownAction,
+  UnsubscribeListener,
+} from '@reduxjs/toolkit'
+import {
+  addListener,
+  configureStore,
+  createAction,
+  createListenerMiddleware,
+  createSlice,
+  isFluxStandardAction,
+} from '@reduxjs/toolkit'
+
+const listenerMiddleware = createListenerMiddleware()
+const { startListening } = listenerMiddleware
+
+const addTypedListenerAction = addListener as TypedAddListener<CounterState>
+
+interface CounterState {
+  value: number
+}
+
+const testAction1 = createAction<string>('testAction1')
+const testAction2 = createAction<string>('testAction2')
+
+const counterSlice = createSlice({
+  name: 'counter',
+  initialState: { value: 0 } as CounterState,
+  reducers: {
+    increment(state) {
+      state.value += 1
+    },
+    decrement(state) {
+      state.value -= 1
+    },
+    // Use the PayloadAction type to declare the contents of `action.payload`
+    incrementByAmount: (state, action: PayloadAction<number>) => {
+      state.value += action.payload
+    },
+  },
+})
+
+const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+describe('type tests', () => {
+  const store = configureStore({
+    reducer: () => 42,
+    middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),
+  })
+
+  test('Allows passing an extra argument on middleware creation', () => {
+    const originalExtra = 42
+    const listenerMiddleware = createListenerMiddleware({
+      extra: originalExtra,
+    })
+    const store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),
+    })
+
+    let foundExtra: number | null = null
+
+    const typedAddListener =
+      listenerMiddleware.startListening as TypedStartListening<
+        CounterState,
+        typeof store.dispatch,
+        typeof originalExtra
+      >
+
+    typedAddListener({
+      matcher: (action): action is Action => true,
+      effect: (action, listenerApi) => {
+        foundExtra = listenerApi.extra
+
+        expectTypeOf(listenerApi.extra).toMatchTypeOf(originalExtra)
+      },
+    })
+
+    store.dispatch(testAction1('a'))
+    expect(foundExtra).toBe(originalExtra)
+  })
+
+  test('unsubscribing via callback from dispatch', () => {
+    const unsubscribe = store.dispatch(
+      addListener({
+        actionCreator: testAction1,
+        effect: () => {},
+      }),
+    )
+
+    expectTypeOf(unsubscribe).toEqualTypeOf<UnsubscribeListener>()
+
+    store.dispatch(testAction1('a'))
+
+    unsubscribe()
+    store.dispatch(testAction2('b'))
+    store.dispatch(testAction1('c'))
+  })
+
+  test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', () => {
+    type ExpectedTakeResultType =
+      | readonly [ReturnType<typeof increment>, CounterState, CounterState]
+      | null
+
+    let timeout: number | undefined = undefined
+    let done = false
+
+    const startAppListening =
+      startListening as TypedStartListening<CounterState>
+    startAppListening({
+      predicate: incrementByAmount.match,
+      effect: async (_, listenerApi) => {
+        let takeResult = await listenerApi.take(increment.match, timeout)
+
+        timeout = 1
+        takeResult = await listenerApi.take(increment.match, timeout)
+        expect(takeResult).toBeNull()
+
+        expectTypeOf(takeResult).toMatchTypeOf<ExpectedTakeResultType>()
+
+        done = true
+      },
+    })
+
+    expect(done).toBe(true)
+  })
+
+  test('State args default to unknown', () => {
+    createListenerEntry({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).toBeUnknown()
+
+        expectTypeOf(previousState).toBeUnknown()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toBeUnknown()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = getState()
+
+          expectTypeOf(thunkState).toBeUnknown()
+        })
+      },
+    })
+
+    startListening({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).toBeUnknown()
+
+        expectTypeOf(previousState).toBeUnknown()
+
+        return true
+      },
+      effect: (action, listenerApi) => {},
+    })
+
+    startListening({
+      matcher: increment.match,
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toBeUnknown()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = getState()
+
+          expectTypeOf(thunkState).toBeUnknown()
+        })
+      },
+    })
+
+    store.dispatch(
+      addListener({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is UnknownAction => {
+          expectTypeOf(currentState).toBeUnknown()
+
+          expectTypeOf(previousState).toBeUnknown()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toBeUnknown()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = getState()
+
+            expectTypeOf(thunkState).toBeUnknown()
+          })
+        },
+      }),
+    )
+
+    store.dispatch(
+      addListener({
+        matcher: increment.match,
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toBeUnknown()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = getState()
+
+            expectTypeOf(thunkState).toBeUnknown()
+          })
+        },
+      }),
+    )
+  })
+
+  test('Action type is inferred from args', () => {
+    startListening({
+      type: 'abcd',
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
+      },
+    })
+
+    startListening({
+      actionCreator: incrementByAmount,
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+      },
+    })
+
+    startListening({
+      matcher: incrementByAmount.match,
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+      },
+    })
+
+    startListening({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is PayloadAction<number> => {
+        return (
+          isFluxStandardAction(action) && typeof action.payload === 'boolean'
+        )
+      },
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
+      },
+    })
+
+    startListening({
+      predicate: (action, currentState) => {
+        return (
+          isFluxStandardAction(action) && typeof action.payload === 'number'
+        )
+      },
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<UnknownAction>()
+      },
+    })
+
+    store.dispatch(
+      addListener({
+        type: 'abcd',
+        effect: (action, listenerApi) => {
+          expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()
+        },
+      }),
+    )
+
+    store.dispatch(
+      addListener({
+        actionCreator: incrementByAmount,
+        effect: (action, listenerApi) => {
+          expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+        },
+      }),
+    )
+
+    store.dispatch(
+      addListener({
+        matcher: incrementByAmount.match,
+        effect: (action, listenerApi) => {
+          expectTypeOf(action).toMatchTypeOf<PayloadAction<number>>()
+        },
+      }),
+    )
+  })
+
+  test('Can create a pre-typed middleware', () => {
+    const typedMiddleware = createListenerMiddleware<CounterState>()
+
+    typedMiddleware.startListening({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).not.toBeAny()
+
+        expectTypeOf(previousState).not.toBeAny()
+
+        expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+        expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    // Can pass a predicate function with fewer args
+    typedMiddleware.startListening({
+      predicate: (action, currentState): action is PayloadAction<number> => {
+        expectTypeOf(currentState).not.toBeAny()
+
+        expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()
+
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    typedMiddleware.startListening({
+      actionCreator: incrementByAmount,
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    store.dispatch(
+      addTypedListenerAction({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is ReturnType<typeof incrementByAmount> => {
+          expectTypeOf(currentState).not.toBeAny()
+
+          expectTypeOf(previousState).not.toBeAny()
+
+          expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+          expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+
+    store.dispatch(
+      addTypedListenerAction({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is UnknownAction => {
+          expectTypeOf(currentState).not.toBeAny()
+
+          expectTypeOf(previousState).not.toBeAny()
+
+          expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+          expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+  })
+
+  test('Can create pre-typed versions of startListening and addListener', () => {
+    const typedAddListener = startListening as TypedStartListening<CounterState>
+    const typedAddListenerAction = addListener as TypedAddListener<CounterState>
+
+    typedAddListener({
+      predicate: (
+        action,
+        currentState,
+        previousState,
+      ): action is UnknownAction => {
+        expectTypeOf(currentState).not.toBeAny()
+
+        expectTypeOf(previousState).not.toBeAny()
+
+        expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+        expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+        return true
+      },
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    typedAddListener({
+      matcher: incrementByAmount.match,
+      effect: (action, listenerApi) => {
+        const listenerState = listenerApi.getState()
+
+        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+        listenerApi.dispatch((dispatch, getState) => {
+          const thunkState = listenerApi.getState()
+
+          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+        })
+      },
+    })
+
+    store.dispatch(
+      typedAddListenerAction({
+        predicate: (
+          action,
+          currentState,
+          previousState,
+        ): action is UnknownAction => {
+          expectTypeOf(currentState).not.toBeAny()
+
+          expectTypeOf(previousState).not.toBeAny()
+
+          expectTypeOf(currentState).toEqualTypeOf<CounterState>()
+
+          expectTypeOf(previousState).toEqualTypeOf<CounterState>()
+
+          return true
+        },
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+
+    store.dispatch(
+      typedAddListenerAction({
+        matcher: incrementByAmount.match,
+        effect: (action, listenerApi) => {
+          const listenerState = listenerApi.getState()
+
+          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()
+
+          listenerApi.dispatch((dispatch, getState) => {
+            const thunkState = listenerApi.getState()
+
+            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()
+          })
+        },
+      }),
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1371 @@
+import {
+  listenerCancelled,
+  listenerCompleted,
+} from '@internal/listenerMiddleware/exceptions'
+import type { AddListenerOverloads } from '@internal/listenerMiddleware/types'
+import { noop } from '@internal/listenerMiddleware/utils'
+import type {
+  Action,
+  ListenerEffect,
+  ListenerEffectAPI,
+  PayloadAction,
+  TypedRemoveListener,
+  TypedStartListening,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  TaskAbortError,
+  addListener,
+  clearAllListeners,
+  configureStore,
+  createAction,
+  createListenerMiddleware,
+  createSlice,
+  isAnyOf,
+  removeListener,
+} from '@reduxjs/toolkit'
+import type { Mock } from 'vitest'
+
+const middlewareApi = {
+  getState: expect.any(Function),
+  getOriginalState: expect.any(Function),
+  condition: expect.any(Function),
+  extra: undefined,
+  take: expect.any(Function),
+  signal: expect.any(Object),
+  fork: expect.any(Function),
+  delay: expect.any(Function),
+  pause: expect.any(Function),
+  dispatch: expect.any(Function),
+  unsubscribe: expect.any(Function),
+  subscribe: expect.any(Function),
+  cancelActiveListeners: expect.any(Function),
+  cancel: expect.any(Function),
+  throwIfCancelled: expect.any(Function),
+}
+
+// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
+export interface Deferred<T> extends Promise<T> {
+  resolve(value?: T | PromiseLike<T>): void
+  // deno-lint-ignore no-explicit-any
+  reject(reason?: any): void
+}
+
+/** Creates a Promise with the `reject` and `resolve` functions
+ * placed as methods on the promise object itself. It allows you to do:
+ *
+ *     const p = deferred<number>();
+ *     // ...
+ *     p.resolve(42);
+ */
+export function deferred<T>(): Deferred<T> {
+  let methods
+  const promise = new Promise<T>((resolve, reject): void => {
+    methods = { resolve, reject }
+  })
+  return Object.assign(promise, methods) as Deferred<T>
+}
+
+describe('createListenerMiddleware', () => {
+  let store = configureStore({
+    reducer: () => 42,
+    middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),
+  })
+
+  interface CounterState {
+    value: number
+  }
+
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: { value: 0 } as CounterState,
+    reducers: {
+      increment(state) {
+        state.value += 1
+      },
+      decrement(state) {
+        state.value -= 1
+      },
+      // Use the PayloadAction type to declare the contents of `action.payload`
+      incrementByAmount: (state, action: PayloadAction<number>) => {
+        state.value += action.payload
+      },
+    },
+  })
+  const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+  function delay(ms: number) {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+  }
+
+  let reducer: Mock
+  let listenerMiddleware = createListenerMiddleware()
+  let { middleware, startListening, stopListening, clearListeners } =
+    listenerMiddleware
+  const removeTypedListenerAction =
+    removeListener as TypedRemoveListener<CounterState>
+
+  const testAction1 = createAction<string>('testAction1')
+  type TestAction1 = ReturnType<typeof testAction1>
+  const testAction2 = createAction<string>('testAction2')
+  type TestAction2 = ReturnType<typeof testAction2>
+  const testAction3 = createAction<string>('testAction3')
+
+  vi.spyOn(console, 'error').mockImplementation(noop)
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    stopListening = listenerMiddleware.stopListening
+    clearListeners = listenerMiddleware.clearListeners
+    reducer = vi.fn(() => ({}))
+    store = configureStore({
+      reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  afterEach(() => {
+    vi.clearAllMocks()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+  })
+
+  describe('Middleware setup', () => {
+    test('Allows passing an extra argument on middleware creation', () => {
+      const originalExtra = 42
+      const listenerMiddleware = createListenerMiddleware({
+        extra: originalExtra,
+      })
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),
+      })
+
+      let foundExtra: number | null = null
+
+      const typedAddListener =
+        listenerMiddleware.startListening as TypedStartListening<
+          CounterState,
+          typeof store.dispatch,
+          typeof originalExtra
+        >
+
+      typedAddListener({
+        matcher: (action): action is Action => true,
+        effect: (action, listenerApi) => {
+          foundExtra = listenerApi.extra
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      expect(foundExtra).toBe(originalExtra)
+    })
+
+    test('Passes through if there are no listeners', () => {
+      const originalAction = testAction1('a')
+      const resultAction = store.dispatch(originalAction)
+      expect(resultAction).toBe(originalAction)
+    })
+  })
+
+  describe('Subscription and unsubscription', () => {
+    test('directly subscribing', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('c'), middlewareApi],
+      ])
+    })
+
+    test('stopListening returns true if an entry has been unsubscribed, false otherwise', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      expect(stopListening({ actionCreator: testAction2, effect })).toBe(false)
+      expect(stopListening({ actionCreator: testAction1, effect })).toBe(true)
+    })
+
+    test('dispatch(removeListener({...})) returns true if an entry has been unsubscribed, false otherwise', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      expect(
+        store.dispatch(
+          removeTypedListenerAction({
+            actionCreator: testAction2,
+            effect,
+          }),
+        ),
+      ).toBe(false)
+      expect(
+        store.dispatch(
+          removeTypedListenerAction({
+            actionCreator: testAction1,
+            effect,
+          }),
+        ),
+      ).toBe(true)
+    })
+
+    test('can subscribe with a string action type', () => {
+      const effect = vi.fn((_: UnknownAction) => {})
+
+      store.dispatch(
+        addListener({
+          type: testAction2.type,
+          effect,
+        }),
+      )
+
+      store.dispatch(testAction2('b'))
+      expect(effect.mock.calls).toEqual([[testAction2('b'), middlewareApi]])
+
+      store.dispatch(removeListener({ type: testAction2.type, effect }))
+
+      store.dispatch(testAction2('b'))
+      expect(effect.mock.calls).toEqual([[testAction2('b'), middlewareApi]])
+    })
+
+    test('can subscribe with a matcher function', () => {
+      const effect = vi.fn((_: UnknownAction) => {})
+
+      const isAction1Or2 = isAnyOf(testAction1, testAction2)
+
+      const unsubscribe = startListening({
+        matcher: isAction1Or2,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction3('c'))
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction2('b'), middlewareApi],
+      ])
+
+      unsubscribe()
+
+      store.dispatch(testAction2('b'))
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction2('b'), middlewareApi],
+      ])
+    })
+
+    test('Can subscribe with an action predicate function', () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let listener1Calls = 0
+
+      startListening({
+        predicate: (action, state) => {
+          return (state as CounterState).value > 1
+        },
+        effect: () => {
+          listener1Calls++
+        },
+      })
+
+      let listener2Calls = 0
+
+      startListening({
+        predicate: (action, state, prevState) => {
+          return (
+            (state as CounterState).value > 1 &&
+            (prevState as CounterState).value % 2 === 0
+          )
+        },
+        effect: () => {
+          listener2Calls++
+        },
+      })
+
+      store.dispatch(increment())
+      store.dispatch(increment())
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      expect(listener1Calls).toBe(3)
+      expect(listener2Calls).toBe(1)
+    })
+
+    test('subscribing with the same listener will not make it trigger twice (like EventTarget.addEventListener())', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('c'), middlewareApi],
+      ])
+    })
+
+    test('subscribing with the same effect but different predicate is allowed', () => {
+      const effect = vi.fn((_: TestAction1 | TestAction2) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+      startListening({
+        actionCreator: testAction2,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction2('b'), middlewareApi],
+      ])
+    })
+
+    test('unsubscribing via callback', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      const unsubscribe = startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      unsubscribe()
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('directly unsubscribing', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+
+      stopListening({ actionCreator: testAction1, effect })
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('unsubscribing without any subscriptions does not trigger an error', () => {
+      stopListening({ matcher: testAction1.match, effect: noop })
+    })
+
+    test('subscribing via action', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      store.dispatch(
+        addListener({
+          actionCreator: testAction1,
+          effect,
+        }),
+      )
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('c'), middlewareApi],
+      ])
+    })
+
+    test('unsubscribing via callback from dispatch', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      const unsubscribe = store.dispatch(
+        addListener({
+          actionCreator: testAction1,
+          effect,
+        }),
+      )
+
+      store.dispatch(testAction1('a'))
+
+      unsubscribe()
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('unsubscribing via action', () => {
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+
+      store.dispatch(removeListener({ actionCreator: testAction1, effect }))
+      store.dispatch(testAction2('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('can cancel an active listener when unsubscribing directly', async () => {
+      let wasCancelled = false
+      const unsubscribe = startListening({
+        actionCreator: testAction1,
+        effect: async (action, listenerApi) => {
+          try {
+            await listenerApi.condition(testAction2.match)
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              wasCancelled = true
+            }
+          }
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      unsubscribe({ cancelActive: true })
+      expect(wasCancelled).toBe(false)
+      await delay(10)
+      expect(wasCancelled).toBe(true)
+    })
+
+    test('can cancel an active listener when unsubscribing via stopListening', async () => {
+      let wasCancelled = false
+      const effect = async (action: any, listenerApi: any) => {
+        try {
+          await listenerApi.condition(testAction2.match)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            wasCancelled = true
+          }
+        }
+      }
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      stopListening({ actionCreator: testAction1, effect, cancelActive: true })
+      expect(wasCancelled).toBe(false)
+      await delay(10)
+      expect(wasCancelled).toBe(true)
+    })
+
+    test('can cancel an active listener when unsubscribing via removeListener', async () => {
+      let wasCancelled = false
+      const effect = async (action: any, listenerApi: any) => {
+        try {
+          await listenerApi.condition(testAction2.match)
+        } catch (err) {
+          if (err instanceof TaskAbortError) {
+            wasCancelled = true
+          }
+        }
+      }
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(
+        removeListener({
+          actionCreator: testAction1,
+          effect,
+          cancelActive: true,
+        }),
+      )
+      expect(wasCancelled).toBe(false)
+      await delay(10)
+      expect(wasCancelled).toBe(true)
+    })
+
+    const addListenerOptions: [
+      string,
+      Omit<
+        AddListenerOverloads<
+          () => void,
+          typeof store.getState,
+          typeof store.dispatch
+        >,
+        'effect' | 'withTypes'
+      >,
+    ][] = [
+      ['predicate', { predicate: () => true }],
+      ['actionCreator', { actionCreator: testAction1 }],
+      ['matcher', { matcher: isAnyOf(testAction1, testAction2) }],
+      ['type', { type: testAction1.type }],
+    ]
+
+    test.each(addListenerOptions)(
+      'add and remove listener with "%s" param correctly',
+      (_, params) => {
+        const effect: ListenerEffect<
+          UnknownAction,
+          typeof store.getState,
+          typeof store.dispatch
+        > = vi.fn()
+
+        startListening({ ...params, effect } as any)
+
+        store.dispatch(testAction1('a'))
+        expect(effect).toBeCalledTimes(1)
+
+        stopListening({ ...params, effect } as any)
+
+        store.dispatch(testAction1('b'))
+        expect(effect).toBeCalledTimes(1)
+      },
+    )
+
+    const unforwardedActions: [string, UnknownAction][] = [
+      [
+        'addListener',
+        addListener({ actionCreator: testAction1, effect: noop }),
+      ],
+      [
+        'removeListener',
+        removeListener({ actionCreator: testAction1, effect: noop }),
+      ],
+    ]
+    test.each(unforwardedActions)(
+      '"%s" is not forwarded to the reducer',
+      (_, action) => {
+        reducer.mockClear()
+
+        store.dispatch(testAction1('a'))
+        store.dispatch(action)
+        store.dispatch(testAction2('b'))
+
+        expect(reducer.mock.calls).toEqual([
+          [{}, testAction1('a')],
+          [{}, testAction2('b')],
+        ])
+      },
+    )
+
+    test('listenerApi.signal has correct reason when listener is cancelled or completes', async () => {
+      const notifyDeferred = createAction<Deferred<string>>('notify-deferred')
+
+      startListening({
+        actionCreator: notifyDeferred,
+        async effect({ payload }, { signal, cancelActiveListeners, delay }) {
+          signal.addEventListener(
+            'abort',
+            () => {
+              payload.resolve(signal.reason)
+            },
+            { once: true },
+          )
+
+          cancelActiveListeners()
+          delay(10)
+        },
+      })
+
+      const deferredCancelledSignalReason = store.dispatch(
+        notifyDeferred(deferred<string>()),
+      ).payload
+      const deferredCompletedSignalReason = store.dispatch(
+        notifyDeferred(deferred<string>()),
+      ).payload
+
+      expect(await deferredCancelledSignalReason).toBe(listenerCancelled)
+      expect(await deferredCompletedSignalReason).toBe(listenerCompleted)
+    })
+
+    test('can self-cancel via middleware api', async () => {
+      const notifyDeferred = createAction<Deferred<string>>('notify-deferred')
+
+      startListening({
+        actionCreator: notifyDeferred,
+        effect: async ({ payload }, { signal, cancel, delay }) => {
+          signal.addEventListener(
+            'abort',
+            () => {
+              payload.resolve(signal.reason)
+            },
+            { once: true },
+          )
+
+          cancel()
+        },
+      })
+
+      const deferredCancelledSignalReason = store.dispatch(
+        notifyDeferred(deferred<string>()),
+      ).payload
+
+      expect(await deferredCancelledSignalReason).toBe(listenerCancelled)
+    })
+
+    test('Can easily check if the listener has been cancelled', async () => {
+      const pauseDeferred = deferred<void>()
+
+      let listenerCancelled = false
+      let listenerStarted = false
+      let listenerCompleted = false
+      let cancelListener: () => void = () => {}
+      let error: TaskAbortError | undefined = undefined
+
+      startListening({
+        actionCreator: testAction1,
+        effect: async ({ payload }, { throwIfCancelled, cancel }) => {
+          cancelListener = cancel
+          try {
+            listenerStarted = true
+            throwIfCancelled()
+            await pauseDeferred
+
+            throwIfCancelled()
+            listenerCompleted = true
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              listenerCancelled = true
+              error = err
+            }
+          }
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      expect(listenerStarted).toBe(true)
+      expect(listenerCompleted).toBe(false)
+      expect(listenerCancelled).toBe(false)
+
+      // Cancel it while the listener is paused at a non-cancel-aware promise
+      cancelListener()
+      pauseDeferred.resolve()
+
+      await delay(10)
+      expect(listenerCompleted).toBe(false)
+      expect(listenerCancelled).toBe(true)
+      expect((error as any)?.message).toBe(
+        'task cancelled (reason: listener-cancelled)',
+      )
+    })
+
+    test('can unsubscribe via middleware api', () => {
+      const effect = vi.fn(
+        (action: TestAction1, api: ListenerEffectAPI<any, any>) => {
+          if (action.payload === 'b') {
+            api.unsubscribe()
+          }
+        },
+      )
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(testAction1('b'))
+      store.dispatch(testAction1('c'))
+
+      expect(effect.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+        [testAction1('b'), middlewareApi],
+      ])
+    })
+
+    test('Can re-subscribe via middleware api', async () => {
+      let numListenerRuns = 0
+      startListening({
+        actionCreator: testAction1,
+        effect: async (action, listenerApi) => {
+          numListenerRuns++
+
+          listenerApi.unsubscribe()
+
+          await listenerApi.condition(testAction2.match)
+
+          listenerApi.subscribe()
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      expect(numListenerRuns).toBe(1)
+
+      store.dispatch(testAction1('a'))
+      expect(numListenerRuns).toBe(1)
+
+      store.dispatch(testAction2('b'))
+      expect(numListenerRuns).toBe(1)
+
+      await delay(5)
+
+      store.dispatch(testAction1('b'))
+      expect(numListenerRuns).toBe(2)
+    })
+  })
+
+  describe('clear listeners', () => {
+    test('dispatch(clearListenerAction()) cancels running listeners and removes all subscriptions', async () => {
+      const listener1Test = deferred()
+      let listener1Calls = 0
+      let listener2Calls = 0
+      let listener3Calls = 0
+
+      startListening({
+        actionCreator: testAction1,
+        async effect(_, listenerApi) {
+          listener1Calls++
+          listenerApi.signal.addEventListener(
+            'abort',
+            () => listener1Test.resolve(listener1Calls),
+            { once: true },
+          )
+          await listenerApi.condition(() => true)
+          listener1Test.reject(new Error('unreachable: listener1Test'))
+        },
+      })
+
+      startListening({
+        actionCreator: clearAllListeners,
+        effect() {
+          listener2Calls++
+        },
+      })
+
+      startListening({
+        predicate: () => true,
+        effect() {
+          listener3Calls++
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      store.dispatch(clearAllListeners())
+      store.dispatch(testAction1('b'))
+      expect(await listener1Test).toBe(1)
+      expect(listener1Calls).toBe(1)
+      expect(listener3Calls).toBe(1)
+      expect(listener2Calls).toBe(0)
+    })
+
+    test('clear() cancels running listeners and removes all subscriptions', async () => {
+      const listener1Test = deferred()
+
+      let listener1Calls = 0
+      let listener2Calls = 0
+
+      startListening({
+        actionCreator: testAction1,
+        async effect(_, listenerApi) {
+          listener1Calls++
+          listenerApi.signal.addEventListener(
+            'abort',
+            () => listener1Test.resolve(listener1Calls),
+            { once: true },
+          )
+          await listenerApi.condition(() => true)
+          listener1Test.reject(new Error('unreachable: listener1Test'))
+        },
+      })
+
+      startListening({
+        actionCreator: testAction2,
+        effect() {
+          listener2Calls++
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+
+      clearListeners()
+      store.dispatch(testAction1('b'))
+      store.dispatch(testAction2('c'))
+
+      expect(listener2Calls).toBe(0)
+      expect(await listener1Test).toBe(1)
+    })
+
+    test('clear() cancels all running forked tasks', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      startListening({
+        actionCreator: testAction1,
+        async effect(_, { fork, dispatch }) {
+          await fork(() => dispatch(incrementByAmount(3))).result
+          dispatch(incrementByAmount(4))
+        },
+      })
+
+      expect(store.getState().value).toBe(0)
+      store.dispatch(testAction1('a'))
+
+      clearListeners()
+
+      await Promise.resolve() // Forked tasks run on the next microtask.
+
+      expect(store.getState().value).toBe(0)
+    })
+  })
+
+  describe('Listener API', () => {
+    test('Passes both getState and getOriginalState in the API', () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let listener1Calls = 0
+      startListening({
+        actionCreator: increment,
+        effect: (action, listenerApi) => {
+          const stateBefore = listenerApi.getOriginalState() as CounterState
+          const currentState = listenerApi.getOriginalState() as CounterState
+
+          listener1Calls++
+          // In the "before" phase, we pass the same state
+          expect(currentState).toBe(stateBefore)
+        },
+      })
+
+      let listener2Calls = 0
+      startListening({
+        actionCreator: increment,
+        effect: (action, listenerApi) => {
+          // TODO getState functions aren't typed right here
+          const stateBefore = listenerApi.getOriginalState() as CounterState
+          const currentState = listenerApi.getOriginalState() as CounterState
+
+          listener2Calls++
+          // In the "after" phase, we pass the new state for `getState`, and still have original state too
+          expect(currentState.value).toBe(stateBefore.value + 1)
+        },
+      })
+
+      store.dispatch(increment())
+
+      expect(listener1Calls).toBe(1)
+      expect(listener2Calls).toBe(1)
+    })
+
+    test('getOriginalState can only be invoked synchronously', async () => {
+      const onError = vi.fn()
+
+      const listenerMiddleware = createListenerMiddleware<CounterState>({
+        onError,
+      })
+      const { middleware, startListening } = listenerMiddleware
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      startListening({
+        actionCreator: increment,
+        async effect(_, listenerApi) {
+          const runIncrementBy = () => {
+            listenerApi.dispatch(
+              counterSlice.actions.incrementByAmount(
+                listenerApi.getOriginalState().value + 2,
+              ),
+            )
+          }
+
+          runIncrementBy()
+
+          await Promise.resolve()
+
+          runIncrementBy()
+        },
+      })
+
+      expect(store.getState()).toEqual({ value: 0 })
+
+      store.dispatch(increment()) // state.value+=1 && trigger listener
+      expect(onError).not.toHaveBeenCalled()
+      expect(store.getState()).toEqual({ value: 3 })
+
+      await delay(0)
+
+      expect(onError).toBeCalledWith(
+        new Error(
+          'listenerMiddleware: getOriginalState can only be called synchronously',
+        ),
+        { raisedBy: 'effect' },
+      )
+      expect(store.getState()).toEqual({ value: 3 })
+    })
+
+    test('by default, actions are forwarded to the store', () => {
+      reducer.mockClear()
+
+      const effect = vi.fn((_: TestAction1) => {})
+
+      startListening({
+        actionCreator: testAction1,
+        effect,
+      })
+
+      store.dispatch(testAction1('a'))
+
+      expect(reducer.mock.calls).toEqual([[{}, testAction1('a')]])
+    })
+
+    test('listenerApi.delay does not trigger unhandledRejections for completed or cancelled listners', async () => {
+      const deferredCompletedEvt = deferred()
+      const deferredCancelledEvt = deferred()
+      const godotPauseTrigger = deferred()
+
+      // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620
+      // This test just fails if an `unhandledRejection` occurs.
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          listenerApi.unsubscribe()
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCompletedEvt.resolve,
+            { once: true },
+          )
+          listenerApi.delay(100) // missing await
+        },
+      })
+
+      startListening({
+        actionCreator: increment,
+        effect: async (_, listenerApi) => {
+          listenerApi.cancelActiveListeners()
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCancelledEvt.resolve,
+            { once: true },
+          )
+          listenerApi.delay(100) // missing await
+          listenerApi.pause(godotPauseTrigger)
+        },
+      })
+
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      expect(await deferredCompletedEvt).toBeDefined()
+      expect(await deferredCancelledEvt).toBeDefined()
+    })
+  })
+
+  describe('Error handling', () => {
+    test('Continues running other listeners if one of them raises an error', () => {
+      const matcher = (action: any): action is any => true
+
+      startListening({
+        matcher,
+        effect: () => {
+          throw new Error('Panic!')
+        },
+      })
+
+      const effect = vi.fn(() => {})
+      startListening({ matcher, effect })
+
+      store.dispatch(testAction1('a'))
+      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])
+    })
+
+    test('Continues running other listeners if a predicate raises an error', () => {
+      const matcher = (action: any): action is any => true
+      const firstListener = vi.fn(() => {})
+      const secondListener = vi.fn(() => {})
+
+      startListening({
+        // @ts-expect-error
+        matcher: (arg: unknown): arg is unknown => {
+          throw new Error('Predicate Panic!')
+        },
+        effect: firstListener,
+      })
+
+      startListening({ matcher, effect: secondListener })
+
+      store.dispatch(testAction1('a'))
+      expect(firstListener).not.toHaveBeenCalled()
+      expect(secondListener.mock.calls).toEqual([
+        [testAction1('a'), middlewareApi],
+      ])
+    })
+
+    test('Notifies sync listener errors to `onError`, if provided', async () => {
+      const onError = vi.fn()
+      const listenerMiddleware = createListenerMiddleware({
+        onError,
+      })
+      const { middleware, startListening } = listenerMiddleware
+      reducer = vi.fn(() => ({}))
+      store = configureStore({
+        reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      const listenerError = new Error('Boom!')
+
+      const matcher = (action: any): action is any => true
+
+      startListening({
+        matcher,
+        effect: () => {
+          throw listenerError
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+      await delay(100)
+
+      expect(onError).toBeCalledWith(listenerError, {
+        raisedBy: 'effect',
+      })
+    })
+
+    test('Notifies async listeners errors to `onError`, if provided', async () => {
+      const onError = vi.fn()
+      const listenerMiddleware = createListenerMiddleware({
+        onError,
+      })
+      const { middleware, startListening } = listenerMiddleware
+      reducer = vi.fn(() => ({}))
+      store = configureStore({
+        reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      const listenerError = new Error('Boom!')
+      const matcher = (action: any): action is any => true
+
+      startListening({
+        matcher,
+        effect: async () => {
+          throw listenerError
+        },
+      })
+
+      store.dispatch(testAction1('a'))
+
+      await delay(100)
+
+      expect(onError).toBeCalledWith(listenerError, {
+        raisedBy: 'effect',
+      })
+    })
+  })
+
+  describe('take and condition methods', () => {
+    test('take resolves to the tuple [A, CurrentState, PreviousState] when the predicate matches the action', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      const typedAddListener = startListening as TypedStartListening<
+        CounterState,
+        typeof store.dispatch
+      >
+      let result:
+        | [ReturnType<typeof increment>, CounterState, CounterState]
+        | null = null
+
+      typedAddListener({
+        predicate: incrementByAmount.match,
+        async effect(_: UnknownAction, listenerApi) {
+          result = await listenerApi.take(increment.match)
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      store.dispatch(increment())
+
+      await delay(10)
+
+      expect(result).toEqual([increment(), { value: 2 }, { value: 1 }])
+    })
+
+    test('take resolves to null if the timeout expires', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let takeResult: any = undefined
+
+      startListening({
+        predicate: incrementByAmount.match,
+        effect: async (_, listenerApi) => {
+          takeResult = await listenerApi.take(increment.match, 15)
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      await delay(25)
+
+      expect(takeResult).toBe(null)
+    })
+
+    test("take resolves to [A, CurrentState, PreviousState] if the timeout is provided but doesn't expire", async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+      let takeResult: any = undefined
+      let stateBefore: any = undefined
+      let stateCurrent: any = undefined
+
+      startListening({
+        predicate: incrementByAmount.match,
+        effect: async (_, listenerApi) => {
+          stateBefore = listenerApi.getState()
+          takeResult = await listenerApi.take(increment.match, 50)
+          stateCurrent = listenerApi.getState()
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      store.dispatch(increment())
+
+      await delay(25)
+      expect(takeResult).toEqual([increment(), stateCurrent, stateBefore])
+    })
+
+    test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let timeout: number | undefined = undefined
+      let done = false
+
+      const startAppListening =
+        startListening as TypedStartListening<CounterState>
+      startAppListening({
+        predicate: incrementByAmount.match,
+        effect: async (_, listenerApi) => {
+          const stateBefore = listenerApi.getState()
+
+          let takeResult = await listenerApi.take(increment.match, timeout)
+          const stateCurrent = listenerApi.getState()
+          expect(takeResult).toEqual([increment(), stateCurrent, stateBefore])
+
+          timeout = 1
+          takeResult = await listenerApi.take(increment.match, timeout)
+          expect(takeResult).toBeNull()
+
+          done = true
+        },
+      })
+      store.dispatch(incrementByAmount(1))
+      store.dispatch(increment())
+
+      await delay(25)
+      expect(done).toBe(true)
+    })
+
+    test('condition method resolves promise when the predicate succeeds', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let finalCount = 0
+      let listenerStarted = false
+
+      startListening({
+        predicate: (action, _, previousState) => {
+          return (
+            increment.match(action) &&
+            (previousState as CounterState).value === 0
+          )
+        },
+        effect: async (action, listenerApi) => {
+          listenerStarted = true
+          const result = await listenerApi.condition((action, currentState) => {
+            return (currentState as CounterState).value === 3
+          })
+
+          expect(result).toBe(true)
+          const latestState = listenerApi.getState() as CounterState
+          finalCount = latestState.value
+        },
+      })
+
+      store.dispatch(increment())
+
+      expect(listenerStarted).toBe(true)
+      await delay(25)
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      await delay(25)
+
+      expect(finalCount).toBe(3)
+    })
+
+    test('condition method resolves promise when there is a timeout', async () => {
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+
+      let finalCount = 0
+      let listenerStarted = false
+
+      startListening({
+        predicate: (action, currentState) => {
+          return (
+            increment.match(action) &&
+            (currentState as CounterState).value === 1
+          )
+        },
+        effect: async (action, listenerApi) => {
+          listenerStarted = true
+          const result = await listenerApi.condition((action, currentState) => {
+            return (currentState as CounterState).value === 3
+          }, 25)
+
+          expect(result).toBe(false)
+          const latestState = listenerApi.getState() as CounterState
+          finalCount = latestState.value
+        },
+      })
+
+      store.dispatch(increment())
+      expect(listenerStarted).toBe(true)
+
+      store.dispatch(increment())
+
+      await delay(50)
+      store.dispatch(increment())
+
+      expect(finalCount).toBe(2)
+    })
+
+    test('take does not trigger unhandledRejections for completed or cancelled tasks', async () => {
+      const deferredCompletedEvt = deferred()
+      const deferredCancelledEvt = deferred()
+      const store = configureStore({
+        reducer: counterSlice.reducer,
+        middleware: (gDM) => gDM().prepend(middleware),
+      })
+      const godotPauseTrigger = deferred()
+
+      startListening({
+        predicate: () => true,
+        effect: async (_, listenerApi) => {
+          listenerApi.unsubscribe() // run once
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCompletedEvt.resolve,
+          )
+          listenerApi.take(() => true) // missing await
+        },
+      })
+
+      startListening({
+        predicate: () => true,
+        effect: async (_, listenerApi) => {
+          listenerApi.cancelActiveListeners()
+          listenerApi.signal.addEventListener(
+            'abort',
+            deferredCancelledEvt.resolve,
+          )
+          listenerApi.take(() => true) // missing await
+          await listenerApi.pause(godotPauseTrigger)
+        },
+      })
+
+      store.dispatch({ type: 'type' })
+      store.dispatch({ type: 'type' })
+      expect(await deferredCompletedEvt).toBeDefined()
+    })
+  })
+
+  describe('Job API', () => {
+    test('Allows canceling previous jobs', async () => {
+      let jobsStarted = 0
+      let jobsContinued = 0
+      let jobsCanceled = 0
+
+      startListening({
+        actionCreator: increment,
+        effect: async (action, listenerApi) => {
+          jobsStarted++
+
+          if (jobsStarted < 3) {
+            try {
+              await listenerApi.condition(decrement.match)
+              // Cancelation _should_ cause `condition()` to throw so we never
+              // end up hitting this next line
+              jobsContinued++
+            } catch (err) {
+              if (err instanceof TaskAbortError) {
+                jobsCanceled++
+              }
+            }
+          } else {
+            listenerApi.cancelActiveListeners()
+          }
+        },
+      })
+
+      store.dispatch(increment())
+      store.dispatch(increment())
+      store.dispatch(increment())
+
+      await delay(10)
+      expect(jobsStarted).toBe(3)
+      expect(jobsContinued).toBe(0)
+      expect(jobsCanceled).toBe(2)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,159 @@
+import type {
+  Action,
+  ThunkAction,
+  TypedAddListener,
+  TypedRemoveListener,
+  TypedStartListening,
+  TypedStopListening,
+} from '@reduxjs/toolkit'
+import {
+  addListener,
+  configureStore,
+  createAsyncThunk,
+  createListenerMiddleware,
+  createSlice,
+  removeListener,
+} from '@reduxjs/toolkit'
+import { describe, expectTypeOf, test } from 'vitest'
+
+export interface CounterState {
+  counter: number
+}
+
+const initialState: CounterState = {
+  counter: 0,
+}
+
+export const counterSlice = createSlice({
+  name: 'counter',
+  initialState,
+  reducers: {
+    increment(state) {
+      state.counter++
+    },
+  },
+})
+
+export function fetchCount(amount = 1) {
+  return new Promise<{ data: number }>((resolve) =>
+    setTimeout(() => resolve({ data: amount }), 500),
+  )
+}
+
+export const incrementAsync = createAsyncThunk(
+  'counter/fetchCount',
+  async (amount: number) => {
+    const response = await fetchCount(amount)
+    // The value we return becomes the `fulfilled` action payload
+    return response.data
+  },
+)
+
+const { increment } = counterSlice.actions
+
+const store = configureStore({
+  reducer: counterSlice.reducer,
+})
+
+type AppStore = typeof store
+type AppDispatch = typeof store.dispatch
+type RootState = ReturnType<typeof store.getState>
+type AppThunk<ThunkReturnType = void> = ThunkAction<
+  ThunkReturnType,
+  RootState,
+  unknown,
+  Action
+>
+type ExtraArgument = { foo: string }
+
+describe('listenerMiddleware.withTypes<RootState, AppDispatch>()', () => {
+  const listenerMiddleware = createListenerMiddleware()
+  let timeout: number | undefined = undefined
+  let done = false
+
+  type ExpectedTakeResultType =
+    | [ReturnType<typeof increment>, RootState, RootState]
+    | null
+
+  test('startListening.withTypes', () => {
+    const startAppListening = listenerMiddleware.startListening.withTypes<
+      RootState,
+      AppDispatch,
+      ExtraArgument
+    >()
+
+    expectTypeOf(startAppListening).toEqualTypeOf<
+      TypedStartListening<RootState, AppDispatch, ExtraArgument>
+    >()
+
+    startAppListening({
+      predicate: increment.match,
+      effect: async (action, listenerApi) => {
+        const stateBefore = listenerApi.getState()
+
+        expectTypeOf(increment).returns.toEqualTypeOf(action)
+
+        expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()
+
+        expectTypeOf(stateBefore).toEqualTypeOf<RootState>()
+
+        let takeResult = await listenerApi.take(increment.match, timeout)
+        const stateCurrent = listenerApi.getState()
+
+        expectTypeOf(takeResult).toEqualTypeOf<ExpectedTakeResultType>()
+
+        expectTypeOf(stateCurrent).toEqualTypeOf<RootState>()
+
+        expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()
+
+        timeout = 1
+        takeResult = await listenerApi.take(increment.match, timeout)
+
+        done = true
+      },
+    })
+  })
+
+  test('addListener.withTypes', () => {
+    const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+    expectTypeOf(addAppListener).toEqualTypeOf<
+      TypedAddListener<RootState, AppDispatch, ExtraArgument>
+    >()
+
+    store.dispatch(
+      addAppListener({
+        matcher: increment.match,
+        effect: (action, listenerApi) => {
+          const state = listenerApi.getState()
+
+          expectTypeOf(state).toEqualTypeOf<RootState>()
+
+          expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()
+
+          expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()
+        },
+      }),
+    )
+  })
+
+  test('removeListener.withTypes', () => {
+    const removeAppListener = removeListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+    expectTypeOf(removeAppListener).toEqualTypeOf<
+      TypedRemoveListener<RootState, AppDispatch, ExtraArgument>
+    >()
+  })
+
+  test('stopListening.withTypes', () => {
+    const stopAppListening = listenerMiddleware.stopListening.withTypes<
+      RootState,
+      AppDispatch,
+      ExtraArgument
+    >()
+
+    expectTypeOf(stopAppListening).toEqualTypeOf<
+      TypedStopListening<RootState, AppDispatch, ExtraArgument>
+    >()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,120 @@
+import type { Action } from 'redux'
+import type { ThunkAction } from 'redux-thunk'
+import { describe, expect, test } from 'vitest'
+import { configureStore } from '../../configureStore'
+import { createAsyncThunk } from '../../createAsyncThunk'
+import { createSlice } from '../../createSlice'
+import { addListener, createListenerMiddleware, removeListener } from '../index'
+
+export interface CounterState {
+  counter: number
+}
+
+const initialState: CounterState = {
+  counter: 0,
+}
+
+export const counterSlice = createSlice({
+  name: 'counter',
+  initialState,
+  reducers: {
+    increment(state) {
+      state.counter++
+    },
+  },
+})
+
+export function fetchCount(amount = 1) {
+  return new Promise<{ data: number }>((resolve) =>
+    setTimeout(() => resolve({ data: amount }), 500),
+  )
+}
+
+export const incrementAsync = createAsyncThunk(
+  'counter/fetchCount',
+  async (amount: number) => {
+    const response = await fetchCount(amount)
+    // The value we return becomes the `fulfilled` action payload
+    return response.data
+  },
+)
+
+const { increment } = counterSlice.actions
+
+const store = configureStore({
+  reducer: counterSlice.reducer,
+})
+
+type AppStore = typeof store
+type AppDispatch = typeof store.dispatch
+type RootState = ReturnType<typeof store.getState>
+type AppThunk<ThunkReturnType = void> = ThunkAction<
+  ThunkReturnType,
+  RootState,
+  unknown,
+  Action
+>
+
+type ExtraArgument = { foo: string }
+
+const listenerMiddleware = createListenerMiddleware()
+
+const startAppListening = listenerMiddleware.startListening.withTypes<
+  RootState,
+  AppDispatch,
+  ExtraArgument
+>()
+
+const stopAppListening = listenerMiddleware.stopListening.withTypes<
+  RootState,
+  AppDispatch,
+  ExtraArgument
+>()
+
+const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+const removeAppListener = removeListener.withTypes<RootState, AppDispatch, ExtraArgument>()
+
+describe('startAppListening.withTypes', () => {
+  test('should return startListening', () => {
+    expect(startAppListening.withTypes).toEqual(expect.any(Function))
+
+    expect(startAppListening.withTypes().withTypes).toEqual(
+      expect.any(Function),
+    )
+
+    expect(startAppListening).toBe(listenerMiddleware.startListening)
+  })
+})
+
+describe('stopAppListening.withTypes', () => {
+  test('should return stopListening', () => {
+    expect(stopAppListening.withTypes).toEqual(expect.any(Function))
+
+    expect(stopAppListening.withTypes().withTypes).toEqual(expect.any(Function))
+
+    expect(stopAppListening).toBe(listenerMiddleware.stopListening)
+  })
+})
+
+describe('addAppListener.withTypes', () => {
+  test('should return addListener', () => {
+    expect(addAppListener.withTypes).toEqual(expect.any(Function))
+
+    expect(addAppListener.withTypes().withTypes).toEqual(expect.any(Function))
+
+    expect(addAppListener).toBe(addListener)
+  })
+})
+
+describe('removeAppListener.withTypes', () => {
+  test('should return removeListener', () => {
+    expect(removeAppListener.withTypes).toEqual(expect.any(Function))
+
+    expect(removeAppListener.withTypes().withTypes).toEqual(
+      expect.any(Function),
+    )
+
+    expect(removeAppListener).toBe(removeListener)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/useCases.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/useCases.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/tests/useCases.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,175 @@
+import {
+  configureStore,
+  createAction,
+  createSlice,
+  isAnyOf,
+} from '@reduxjs/toolkit'
+
+import type { PayloadAction } from '@reduxjs/toolkit'
+
+import { createListenerMiddleware } from '../index'
+
+import type { TypedAddListener } from '../index'
+import { TaskAbortError } from '../exceptions'
+
+interface CounterState {
+  value: number
+}
+
+const counterSlice = createSlice({
+  name: 'counter',
+  initialState: { value: 0 } as CounterState,
+  reducers: {
+    increment(state) {
+      state.value += 1
+    },
+    decrement(state) {
+      state.value -= 1
+    },
+    // Use the PayloadAction type to declare the contents of `action.payload`
+    incrementByAmount: (state, action: PayloadAction<number>) => {
+      state.value += action.payload
+    },
+  },
+})
+const { increment, decrement, incrementByAmount } = counterSlice.actions
+
+describe('Saga-style Effects Scenarios', () => {
+  let listenerMiddleware = createListenerMiddleware<CounterState>()
+  let { middleware, startListening, stopListening } = listenerMiddleware
+
+  let store = configureStore({
+    reducer: counterSlice.reducer,
+    middleware: (gDM) => gDM().prepend(middleware),
+  })
+
+  const testAction1 = createAction<string>('testAction1')
+  type TestAction1 = ReturnType<typeof testAction1>
+  const testAction2 = createAction<string>('testAction2')
+  type TestAction2 = ReturnType<typeof testAction2>
+  const testAction3 = createAction<string>('testAction3')
+  type TestAction3 = ReturnType<typeof testAction3>
+
+  type RootState = ReturnType<typeof store.getState>
+
+  function delay(ms: number) {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+  }
+
+  beforeEach(() => {
+    listenerMiddleware = createListenerMiddleware<CounterState>()
+    middleware = listenerMiddleware.middleware
+    startListening = listenerMiddleware.startListening
+    store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(middleware),
+    })
+  })
+
+  test('Long polling loop', async () => {
+    // Reimplementation of a saga-based long-polling loop that is controlled
+    // by "start/stop" actions. The infinite loop waits for a message from the
+    // server, processes it somehow, and waits for the next message.
+    // Ref: https://gist.github.com/markerikson/5203e71a69fa9dff203c9e27c3d84154
+    const eventPollingStarted = createAction('serverPolling/started')
+    const eventPollingStopped = createAction('serverPolling/stopped')
+
+    // For this example, we're going to fake up a "server event poll" async
+    // function by wrapping an event emitter so that every call returns a
+    // promise that is resolved the next time an event is emitted.
+    // This is the tiniest event emitter I could find to copy-paste in here.
+    let createNanoEvents = () => ({
+      events: {} as Record<string, any>,
+      emit(event: string, ...args: any[]) {
+        ;(this.events[event] || []).forEach((i: any) => i(...args))
+      },
+      on(event: string, cb: (...args: any[]) => void) {
+        ;(this.events[event] = this.events[event] || []).push(cb)
+        return () =>
+          (this.events[event] = (this.events[event] || []).filter(
+            (l: any) => l !== cb,
+          ))
+      },
+    })
+    const emitter = createNanoEvents()
+
+    // Rig up a dummy "receive a message from the server" API we can trigger manually
+    function pollForEvent() {
+      return new Promise<{ type: string }>((resolve, reject) => {
+        const unsubscribe = emitter.on('serverEvent', (arg1: string) => {
+          unsubscribe()
+          resolve({ type: arg1 })
+        })
+      })
+    }
+
+    // Track how many times each message was processed by the loop
+    const receivedMessages = {
+      a: 0,
+      b: 0,
+      c: 0,
+    }
+
+    let pollingTaskStarted = false
+    let pollingTaskCanceled = false
+
+    startListening({
+      actionCreator: eventPollingStarted,
+      effect: async (action, listenerApi) => {
+        listenerApi.unsubscribe()
+
+        // Start a child job that will infinitely loop receiving messages
+        const pollingTask = listenerApi.fork(async (forkApi) => {
+          pollingTaskStarted = true
+          try {
+            while (true) {
+              // Cancelation-aware pause for a new server message
+              const serverEvent = await forkApi.pause(pollForEvent())
+              // Process the message. In this case, just count the times we've seen this message.
+              if (serverEvent.type in receivedMessages) {
+                receivedMessages[
+                  serverEvent.type as keyof typeof receivedMessages
+                ]++
+              }
+            }
+          } catch (err) {
+            if (err instanceof TaskAbortError) {
+              pollingTaskCanceled = true
+            }
+          }
+          return 0
+        })
+
+        // Wait for the "stop polling" action
+        await listenerApi.condition(eventPollingStopped.match)
+        pollingTask.cancel()
+      },
+    })
+
+    store.dispatch(eventPollingStarted())
+    await delay(5)
+    expect(pollingTaskStarted).toBe(true)
+
+    await delay(5)
+    emitter.emit('serverEvent', 'a')
+    // Promise resolution
+    await delay(1)
+    emitter.emit('serverEvent', 'b')
+    // Promise resolution
+    await delay(1)
+
+    store.dispatch(eventPollingStopped())
+
+    // Have to break out of the event loop to let the cancelation promise
+    // kick in - emitting before this would still resolve pollForEvent()
+    await delay(1)
+    emitter.emit('serverEvent', 'c')
+
+    // A and B were processed earlier. The first C was processed because the
+    // emitter synchronously resolved the `pollForEvents` promise before
+    // the cancelation took effect, but after another pause, the
+    // cancelation kicked in and the second C is ignored.
+    expect(receivedMessages).toEqual({ a: 1, b: 1, c: 0 })
+    expect(pollingTaskCanceled).toBe(true)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/types.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,872 @@
+import type {
+  Action,
+  Dispatch,
+  Middleware,
+  MiddlewareAPI,
+  UnknownAction,
+} from 'redux'
+import type { ThunkDispatch } from 'redux-thunk'
+import type { BaseActionCreator, PayloadAction } from '../createAction'
+import type { TypedActionCreator } from '../mapBuilders'
+import type { TaskAbortError } from './exceptions'
+
+/**
+ * Types copied from RTK
+ */
+
+/** @internal */
+type TypedActionCreatorWithMatchFunction<Type extends string> =
+  TypedActionCreator<Type> & {
+    match: MatchFunction<any>
+  }
+
+/** @internal */
+export type AnyListenerPredicate<State> = (
+  action: UnknownAction,
+  currentState: State,
+  originalState: State,
+) => boolean
+
+/** @public */
+export type ListenerPredicate<ActionType extends Action, State> = (
+  action: UnknownAction,
+  currentState: State,
+  originalState: State,
+) => action is ActionType
+
+/** @public */
+export interface ConditionFunction<State> {
+  (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>
+  (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>
+  (predicate: () => boolean, timeout?: number): Promise<boolean>
+}
+
+/** @internal */
+export type MatchFunction<T> = (v: any) => v is T
+
+/** @public */
+export interface ForkedTaskAPI {
+  /**
+   * Returns a promise that resolves when `waitFor` resolves or
+   * rejects if the task or the parent listener has been cancelled or is completed.
+   */
+  pause<W>(waitFor: Promise<W>): Promise<W>
+  /**
+   * Returns a promise that resolves after `timeoutMs` or
+   * rejects if the task or the parent listener has been cancelled or is completed.
+   * @param timeoutMs
+   */
+  delay(timeoutMs: number): Promise<void>
+  /**
+   * An abort signal whose `aborted` property is set to `true`
+   * if the task execution is either aborted or completed.
+   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+   */
+  signal: AbortSignal
+}
+
+/** @public */
+export interface AsyncTaskExecutor<T> {
+  (forkApi: ForkedTaskAPI): Promise<T>
+}
+
+/** @public */
+export interface SyncTaskExecutor<T> {
+  (forkApi: ForkedTaskAPI): T
+}
+
+/** @public */
+export type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>
+
+/** @public */
+export type TaskResolved<T> = {
+  readonly status: 'ok'
+  readonly value: T
+}
+
+/** @public */
+export type TaskRejected = {
+  readonly status: 'rejected'
+  readonly error: unknown
+}
+
+/** @public */
+export type TaskCancelled = {
+  readonly status: 'cancelled'
+  readonly error: TaskAbortError
+}
+
+/** @public */
+export type TaskResult<Value> =
+  | TaskResolved<Value>
+  | TaskRejected
+  | TaskCancelled
+
+/** @public */
+export interface ForkedTask<T> {
+  /**
+   * A promise that resolves when the task is either completed or cancelled or rejects
+   * if parent listener execution is cancelled or completed.
+   *
+   * ### Example
+   * ```ts
+   * const result = await fork(async (forkApi) => Promise.resolve(4)).result
+   *
+   * if(result.status === 'ok') {
+   *   console.log(result.value) // logs 4
+   * }}
+   * ```
+   */
+  result: Promise<TaskResult<T>>
+  /**
+   * Cancel task if it is in progress or not yet started,
+   * it is noop otherwise.
+   */
+  cancel(): void
+}
+
+/** @public */
+export interface ForkOptions {
+  /**
+   * If true, causes the parent task to not be marked as complete until
+   * all autoJoined forks have completed or failed.
+   */
+  autoJoin: boolean
+}
+
+/** @public */
+export interface ListenerEffectAPI<
+  State,
+  DispatchType extends Dispatch,
+  ExtraArgument = unknown,
+> extends MiddlewareAPI<DispatchType, State> {
+  /**
+   * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
+   *
+   * ### Synchronous invocation
+   *
+   * This function can **only** be invoked **synchronously**, it throws error otherwise.
+   *
+   * @example
+   *
+   * ```ts
+   * middleware.startListening({
+   *  predicate: () => true,
+   *  async effect(_, { getOriginalState }) {
+   *    getOriginalState(); // sync: OK!
+   *
+   *    setTimeout(getOriginalState, 0); // async: throws Error
+   *
+   *    await Promise().resolve();
+   *
+   *    getOriginalState() // async: throws Error
+   *  }
+   * })
+   * ```
+   */
+  getOriginalState: () => State
+  /**
+   * Removes the listener entry from the middleware and prevent future instances of the listener from running.
+   *
+   * It does **not** cancel any active instances.
+   */
+  unsubscribe(): void
+  /**
+   * It will subscribe a listener if it was previously removed, noop otherwise.
+   */
+  subscribe(): void
+  /**
+   * Returns a promise that resolves when the input predicate returns `true` or
+   * rejects if the listener has been cancelled or is completed.
+   *
+   * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
+   *
+   * ### Example
+   *
+   * ```ts
+   * const updateBy = createAction<number>('counter/updateBy');
+   *
+   * middleware.startListening({
+   *  actionCreator: updateBy,
+   *  async effect(_, { condition }) {
+   *    // wait at most 3s for `updateBy` actions.
+   *    if(await condition(updateBy.match, 3_000)) {
+   *      // `updateBy` has been dispatched twice in less than 3s.
+   *    }
+   *  }
+   * })
+   * ```
+   */
+  condition: ConditionFunction<State>
+  /**
+   * Returns a promise that resolves when the input predicate returns `true` or
+   * rejects if the listener has been cancelled or is completed.
+   *
+   * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
+   *
+   * The promise resolves to null if a timeout is provided and expires first,
+   *
+   * ### Example
+   *
+   * ```ts
+   * const updateBy = createAction<number>('counter/updateBy');
+   *
+   * middleware.startListening({
+   *  actionCreator: updateBy,
+   *  async effect(_, { take }) {
+   *    const [{ payload }] =  await take(updateBy.match);
+   *    console.log(payload); // logs 5;
+   *  }
+   * })
+   *
+   * store.dispatch(updateBy(5));
+   * ```
+   */
+  take: TakePattern<State>
+  /**
+   * Cancels all other running instances of this same listener except for the one that made this call.
+   */
+  cancelActiveListeners: () => void
+  /**
+   * Cancels the instance of this listener that made this call.
+   */
+  cancel: () => void
+  /**
+   * Throws a `TaskAbortError` if this listener has been cancelled
+   */
+  throwIfCancelled: () => void
+  /**
+   * An abort signal whose `aborted` property is set to `true`
+   * if the listener execution is either aborted or completed.
+   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
+   */
+  signal: AbortSignal
+  /**
+   * Returns a promise that resolves after `timeoutMs` or
+   * rejects if the listener has been cancelled or is completed.
+   */
+  delay(timeoutMs: number): Promise<void>
+  /**
+   * Queues in the next microtask the execution of a task.
+   * @param executor
+   * @param options
+   */
+  fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>
+  /**
+   * Returns a promise that resolves when `waitFor` resolves or
+   * rejects if the listener has been cancelled or is completed.
+   * @param promise
+   */
+  pause<M>(promise: Promise<M>): Promise<M>
+  extra: ExtraArgument
+}
+
+/** @public */
+export type ListenerEffect<
+  ActionType extends Action,
+  State,
+  DispatchType extends Dispatch,
+  ExtraArgument = unknown,
+> = (
+  action: ActionType,
+  api: ListenerEffectAPI<State, DispatchType, ExtraArgument>,
+) => void | Promise<void>
+
+/**
+ * @public
+ * Additional infos regarding the error raised.
+ */
+export interface ListenerErrorInfo {
+  /**
+   * Which function has generated the exception.
+   */
+  raisedBy: 'effect' | 'predicate'
+}
+
+/**
+ * @public
+ * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
+ * @param error The thrown error.
+ * @param errorInfo Additional information regarding the thrown error.
+ */
+export interface ListenerErrorHandler {
+  (error: unknown, errorInfo: ListenerErrorInfo): void
+}
+
+/** @public */
+export interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
+  extra?: ExtraArgument
+  /**
+   * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
+   */
+  onError?: ListenerErrorHandler
+}
+
+/** @public */
+export type ListenerMiddleware<
+  State = unknown,
+  DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<
+    State,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = Middleware<
+  {
+    (action: Action<'listenerMiddleware/add'>): UnsubscribeListener
+  },
+  State,
+  DispatchType
+>
+
+/** @public */
+export interface ListenerMiddlewareInstance<
+  StateType = unknown,
+  DispatchType extends ThunkDispatch<
+    StateType,
+    unknown,
+    Action
+  > = ThunkDispatch<StateType, unknown, UnknownAction>,
+  ExtraArgument = unknown,
+> {
+  middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>
+
+  startListening: AddListenerOverloads<
+    UnsubscribeListener,
+    StateType,
+    DispatchType,
+    ExtraArgument
+  > &
+    TypedStartListening<StateType, DispatchType, ExtraArgument>
+
+  stopListening: RemoveListenerOverloads<StateType, DispatchType> &
+    TypedStopListening<StateType, DispatchType>
+
+  /**
+   * Unsubscribes all listeners, cancels running listeners and tasks.
+   */
+  clearListeners: () => void
+}
+
+/**
+ * API Function Overloads
+ */
+
+/** @public */
+export type TakePatternOutputWithoutTimeout<
+  State,
+  Predicate extends AnyListenerPredicate<State>,
+> =
+  Predicate extends MatchFunction<infer ActionType>
+    ? Promise<[ActionType, State, State]>
+    : Promise<[UnknownAction, State, State]>
+
+/** @public */
+export type TakePatternOutputWithTimeout<
+  State,
+  Predicate extends AnyListenerPredicate<State>,
+> =
+  Predicate extends MatchFunction<infer ActionType>
+    ? Promise<[ActionType, State, State] | null>
+    : Promise<[UnknownAction, State, State] | null>
+
+/** @public */
+export interface TakePattern<State> {
+  <Predicate extends AnyListenerPredicate<State>>(
+    predicate: Predicate,
+  ): TakePatternOutputWithoutTimeout<State, Predicate>
+  <Predicate extends AnyListenerPredicate<State>>(
+    predicate: Predicate,
+    timeout: number,
+  ): TakePatternOutputWithTimeout<State, Predicate>
+  <Predicate extends AnyListenerPredicate<State>>(
+    predicate: Predicate,
+    timeout?: number | undefined,
+  ): TakePatternOutputWithTimeout<State, Predicate>
+}
+
+/** @public */
+export interface UnsubscribeListenerOptions {
+  cancelActive?: true
+}
+
+/** @public */
+export type UnsubscribeListener = (
+  unsubscribeOptions?: UnsubscribeListenerOptions,
+) => void
+
+/**
+ * @public
+ * The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
+ */
+export type AddListenerOverloads<
+  Return,
+  StateType = unknown,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+  AdditionalOptions = unknown,
+> = {
+  /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
+  <
+    MiddlewareActionType extends UnknownAction,
+    ListenerPredicateType extends ListenerPredicate<
+      MiddlewareActionType,
+      StateType
+    >,
+  >(
+    options: {
+      actionCreator?: never
+      type?: never
+      matcher?: never
+      predicate: ListenerPredicateType
+      effect: ListenerEffect<
+        ListenerPredicateGuardedActionType<ListenerPredicateType>,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts an RTK action creator, like `incrementByAmount` */
+  <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(
+    options: {
+      actionCreator: ActionCreatorType
+      type?: never
+      matcher?: never
+      predicate?: never
+      effect: ListenerEffect<
+        ReturnType<ActionCreatorType>,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts a specific action type string */
+  <T extends string>(
+    options: {
+      actionCreator?: never
+      type: T
+      matcher?: never
+      predicate?: never
+      effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
+  <MatchFunctionType extends MatchFunction<UnknownAction>>(
+    options: {
+      actionCreator?: never
+      type?: never
+      matcher: MatchFunctionType
+      predicate?: never
+      effect: ListenerEffect<
+        GuardedType<MatchFunctionType>,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+
+  /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
+  <ListenerPredicateType extends AnyListenerPredicate<StateType>>(
+    options: {
+      actionCreator?: never
+      type?: never
+      matcher?: never
+      predicate: ListenerPredicateType
+      effect: ListenerEffect<
+        UnknownAction,
+        StateType,
+        DispatchType,
+        ExtraArgument
+      >
+    } & AdditionalOptions,
+  ): Return
+}
+
+/** @public */
+export type RemoveListenerOverloads<
+  StateType = unknown,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = AddListenerOverloads<
+  boolean,
+  StateType,
+  DispatchType,
+  ExtraArgument,
+  UnsubscribeListenerOptions
+>
+
+/** @public */
+export interface RemoveListenerAction<
+  ActionType extends UnknownAction,
+  State,
+  DispatchType extends Dispatch,
+> {
+  type: 'listenerMiddleware/remove'
+  payload: {
+    type: string
+    listener: ListenerEffect<ActionType, State, DispatchType>
+  }
+}
+
+/**
+ * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedAddListener<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+  Payload = ListenerEntry<StateType, DispatchType>,
+  T extends string = 'listenerMiddleware/add',
+> = BaseActionCreator<Payload, T> &
+  AddListenerOverloads<
+    PayloadAction<Payload, T>,
+    StateType,
+    DispatchType,
+    ExtraArgument
+  > & {
+    /**
+     * Creates a "pre-typed" version of `addListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `addListener` call.
+     *
+     * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
+     *
+     * @example
+     * ```ts
+     * import { addListener } from '@reduxjs/toolkit'
+     *
+     * export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <
+      OverrideStateType extends StateType,
+      OverrideDispatchType extends Dispatch = ThunkDispatch<
+        OverrideStateType,
+        unknown,
+        UnknownAction
+      >,
+      OverrideExtraArgument = unknown,
+    >() => TypedAddListener<
+      OverrideStateType,
+      OverrideDispatchType,
+      OverrideExtraArgument
+    >
+  }
+
+/**
+ * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedRemoveListener<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+  Payload = ListenerEntry<StateType, DispatchType>,
+  T extends string = 'listenerMiddleware/remove',
+> = BaseActionCreator<Payload, T> &
+  AddListenerOverloads<
+    PayloadAction<Payload, T>,
+    StateType,
+    DispatchType,
+    ExtraArgument,
+    UnsubscribeListenerOptions
+  > & {
+    /**
+     * Creates a "pre-typed" version of `removeListener`
+     * where the `state`, `dispatch` and `extra` types are predefined.
+     *
+     * This allows you to set the `state`, `dispatch` and `extra` types once,
+     * eliminating the need to specify them with every `removeListener` call.
+     *
+     * @returns A pre-typed `removeListener` with the state, dispatch and extra
+     * types already defined.
+     *
+     * @example
+     * ```ts
+     * import { removeListener } from '@reduxjs/toolkit'
+     *
+     * export const removeAppListener = removeListener.withTypes<
+     *   RootState,
+     *   AppDispatch,
+     *   ExtraArguments
+     * >()
+     * ```
+     *
+     * @template OverrideStateType - The specific type of state the middleware listener operates on.
+     * @template OverrideDispatchType - The specific type of the dispatch function.
+     * @template OverrideExtraArgument - The specific type of the extra object.
+     *
+     * @since 2.1.0
+     */
+    withTypes: <
+      OverrideStateType extends StateType,
+      OverrideDispatchType extends Dispatch = ThunkDispatch<
+        OverrideStateType,
+        unknown,
+        UnknownAction
+      >,
+      OverrideExtraArgument = unknown,
+    >() => TypedRemoveListener<
+      OverrideStateType,
+      OverrideDispatchType,
+      OverrideExtraArgument
+    >
+  }
+
+/**
+ * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedStartListening<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = AddListenerOverloads<
+  UnsubscribeListener,
+  StateType,
+  DispatchType,
+  ExtraArgument
+> & {
+  /**
+   * Creates a "pre-typed" version of
+   * {@linkcode ListenerMiddlewareInstance.startListening startListening}
+   * where the `state`, `dispatch` and `extra` types are predefined.
+   *
+   * This allows you to set the `state`, `dispatch` and `extra` types once,
+   * eliminating the need to specify them with every
+   * {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
+   *
+   * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
+   *
+   * @example
+   * ```ts
+   * import { createListenerMiddleware } from '@reduxjs/toolkit'
+   *
+   * const listenerMiddleware = createListenerMiddleware()
+   *
+   * export const startAppListening = listenerMiddleware.startListening.withTypes<
+   *   RootState,
+   *   AppDispatch,
+   *   ExtraArguments
+   * >()
+   * ```
+   *
+   * @template OverrideStateType - The specific type of state the middleware listener operates on.
+   * @template OverrideDispatchType - The specific type of the dispatch function.
+   * @template OverrideExtraArgument - The specific type of the extra object.
+   *
+   * @since 2.1.0
+   */
+  withTypes: <
+    OverrideStateType extends StateType,
+    OverrideDispatchType extends Dispatch = ThunkDispatch<
+      OverrideStateType,
+      unknown,
+      UnknownAction
+    >,
+    OverrideExtraArgument = unknown,
+  >() => TypedStartListening<
+    OverrideStateType,
+    OverrideDispatchType,
+    OverrideExtraArgument
+  >
+}
+
+/**
+ * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedStopListening<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
+  /**
+   * Creates a "pre-typed" version of
+   * {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
+   * where the `state`, `dispatch` and `extra` types are predefined.
+   *
+   * This allows you to set the `state`, `dispatch` and `extra` types once,
+   * eliminating the need to specify them with every
+   * {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
+   *
+   * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
+   *
+   * @example
+   * ```ts
+   * import { createListenerMiddleware } from '@reduxjs/toolkit'
+   *
+   * const listenerMiddleware = createListenerMiddleware()
+   *
+   * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
+   *   RootState,
+   *   AppDispatch,
+   *   ExtraArguments
+   * >()
+   * ```
+   *
+   * @template OverrideStateType - The specific type of state the middleware listener operates on.
+   * @template OverrideDispatchType - The specific type of the dispatch function.
+   * @template OverrideExtraArgument - The specific type of the extra object.
+   *
+   * @since 2.1.0
+   */
+  withTypes: <
+    OverrideStateType extends StateType,
+    OverrideDispatchType extends Dispatch = ThunkDispatch<
+      OverrideStateType,
+      unknown,
+      UnknownAction
+    >,
+    OverrideExtraArgument = unknown,
+  >() => TypedStopListening<
+    OverrideStateType,
+    OverrideDispatchType,
+    OverrideExtraArgument
+  >
+}
+
+/**
+ * A "pre-typed" version of `createListenerEntry`, so the listener args are well-typed
+ *
+ * @public
+ */
+export type TypedCreateListenerEntry<
+  StateType,
+  DispatchType extends Dispatch = ThunkDispatch<
+    StateType,
+    unknown,
+    UnknownAction
+  >,
+  ExtraArgument = unknown,
+> = AddListenerOverloads<
+  ListenerEntry<StateType, DispatchType>,
+  StateType,
+  DispatchType,
+  ExtraArgument
+> & {
+  /**
+   * Creates a "pre-typed" version of `createListenerEntry`
+   * where the `state`, `dispatch` and `extra` types are predefined.
+   *
+   * This allows you to set the `state`, `dispatch` and `extra` types once, eliminating
+   * the need to specify them with every `createListenerEntry` call.
+   *
+   * @returns A pre-typed `createListenerEntry` with the state, dispatch and extra
+   * types already defined.
+   *
+   * @example
+   * ```ts
+   * import { createListenerEntry } from '@reduxjs/toolkit'
+   *
+   * export const createAppListenerEntry = createListenerEntry.withTypes<
+   *   RootState,
+   *   AppDispatch,
+   *   ExtraArguments
+   * >()
+   * ```
+   *
+   * @template OverrideStateType - The specific type of state the middleware listener operates on.
+   * @template OverrideDispatchType - The specific type of the dispatch function.
+   * @template OverrideExtraArgument - The specific type of the extra object.
+   *
+   * @since 2.1.0
+   */
+  withTypes: <
+    OverrideStateType extends StateType,
+    OverrideDispatchType extends Dispatch = ThunkDispatch<
+      OverrideStateType,
+      unknown,
+      UnknownAction
+    >,
+    OverrideExtraArgument = unknown,
+  >() => TypedStopListening<
+    OverrideStateType,
+    OverrideDispatchType,
+    OverrideExtraArgument
+  >
+}
+
+/**
+ * Internal Types
+ */
+
+/** @internal An single listener entry */
+export type ListenerEntry<
+  State = unknown,
+  DispatchType extends Dispatch = Dispatch,
+> = {
+  id: string
+  effect: ListenerEffect<any, State, DispatchType>
+  unsubscribe: () => void
+  pending: Set<AbortController>
+  type?: string
+  predicate: ListenerPredicate<UnknownAction, State>
+}
+
+/**
+ * @internal
+ * A shorthand form of the accepted args, solely so that `createListenerEntry` has validly-typed conditional logic when checking the options contents
+ */
+export type FallbackAddListenerOptions = {
+  actionCreator?: TypedActionCreatorWithMatchFunction<string>
+  type?: string
+  matcher?: MatchFunction<any>
+  predicate?: ListenerPredicate<any, any>
+} & { effect: ListenerEffect<any, any, any> }
+
+/**
+ * Utility Types
+ */
+
+/** @public */
+export type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T
+  ? T
+  : never
+
+/** @public */
+export type ListenerPredicateGuardedActionType<T> =
+  T extends ListenerPredicate<infer ActionType, any> ? ActionType : never
Index: node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/listenerMiddleware/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,30 @@
+export const assertFunction: (
+  func: unknown,
+  expected: string,
+) => asserts func is (...args: unknown[]) => unknown = (
+  func: unknown,
+  expected: string,
+) => {
+  if (typeof func !== 'function') {
+    throw new TypeError(`${expected} is not a function`)
+  }
+}
+
+export const noop = () => {}
+
+export const catchRejection = <T>(
+  promise: Promise<T>,
+  onError = noop,
+): Promise<T> => {
+  promise.catch(onError)
+
+  return promise
+}
+
+export const addAbortSignalListener = (
+  abortSignal: AbortSignal,
+  callback: (evt: Event) => void,
+) => {
+  abortSignal.addEventListener('abort', callback, { once: true })
+  return () => abortSignal.removeEventListener('abort', callback)
+}
Index: node_modules/@reduxjs/toolkit/src/mapBuilders.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/mapBuilders.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/mapBuilders.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,299 @@
+import type { Action } from 'redux'
+import type {
+  CaseReducer,
+  CaseReducers,
+  ActionMatcherDescriptionCollection,
+} from './createReducer'
+import type { TypeGuard } from './tsHelpers'
+import type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk'
+
+export type AsyncThunkReducers<
+  State,
+  ThunkArg extends any,
+  Returned = unknown,
+  ThunkApiConfig extends AsyncThunkConfig = {},
+> = {
+  pending?: CaseReducer<
+    State,
+    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>
+  >
+  rejected?: CaseReducer<
+    State,
+    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>
+  >
+  fulfilled?: CaseReducer<
+    State,
+    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>
+  >
+  settled?: CaseReducer<
+    State,
+    ReturnType<
+      AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']
+    >
+  >
+}
+
+export type TypedActionCreator<Type extends string> = {
+  (...args: any[]): Action<Type>
+  type: Type
+}
+
+/**
+ * A builder for an action <-> reducer map.
+ *
+ * @public
+ */
+export interface ActionReducerMapBuilder<State> {
+  /**
+   * Adds a case reducer to handle a single exact action type.
+   * @remarks
+   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<ActionCreator extends TypedActionCreator<string>>(
+    actionCreator: ActionCreator,
+    reducer: CaseReducer<State, ReturnType<ActionCreator>>,
+  ): ActionReducerMapBuilder<State>
+  /**
+   * Adds a case reducer to handle a single exact action type.
+   * @remarks
+   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
+   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
+   * @param reducer - The actual case reducer function.
+   */
+  addCase<Type extends string, A extends Action<Type>>(
+    type: Type,
+    reducer: CaseReducer<State, A>,
+  ): ActionReducerMapBuilder<State>
+
+  /**
+   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.
+   * @remarks
+   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
+   * @param asyncThunk - The async thunk action creator itself.
+   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
+   * @example
+```ts no-transpile
+import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'
+
+const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
+  const response = await fetch(`https://reqres.in/api/users/${id}`)
+  return (await response.json()).data
+})
+
+const reducer = createReducer(initialState, (builder) => {
+  builder.addAsyncThunk(fetchUserById, {
+    pending: (state, action) => {
+      state.fetchUserById.loading = 'pending'
+    },
+    fulfilled: (state, action) => {
+      state.fetchUserById.data = action.payload
+    },
+    rejected: (state, action) => {
+      state.fetchUserById.error = action.error
+    },
+    settled: (state, action) => {
+      state.fetchUserById.loading = action.meta.requestStatus
+    },
+  })
+})
+   */
+  addAsyncThunk<
+    Returned,
+    ThunkArg,
+    ThunkApiConfig extends AsyncThunkConfig = {},
+  >(
+    asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,
+    reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>,
+  ): Omit<ActionReducerMapBuilder<State>, 'addCase'>
+
+  /**
+   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
+   * @remarks
+   * If multiple matcher reducers match, all of them will be executed in the order
+   * they were defined in - even if a case reducer already matched.
+   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
+   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
+   *   function
+   * @param reducer - The actual case reducer function.
+   *
+   * @example
+```ts
+import {
+  createAction,
+  createReducer,
+  AsyncThunk,
+  UnknownAction,
+} from "@reduxjs/toolkit";
+
+type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
+
+type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
+type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
+type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
+
+const initialState: Record<string, string> = {};
+const resetAction = createAction("reset-tracked-loading-state");
+
+function isPendingAction(action: UnknownAction): action is PendingAction {
+  return typeof action.type === "string" && action.type.endsWith("/pending");
+}
+
+const reducer = createReducer(initialState, (builder) => {
+  builder
+    .addCase(resetAction, () => initialState)
+    // matcher can be defined outside as a type predicate function
+    .addMatcher(isPendingAction, (state, action) => {
+      state[action.meta.requestId] = "pending";
+    })
+    .addMatcher(
+      // matcher can be defined inline as a type predicate function
+      (action): action is RejectedAction => action.type.endsWith("/rejected"),
+      (state, action) => {
+        state[action.meta.requestId] = "rejected";
+      }
+    )
+    // matcher can just return boolean and the matcher can receive a generic argument
+    .addMatcher<FulfilledAction>(
+      (action) => action.type.endsWith("/fulfilled"),
+      (state, action) => {
+        state[action.meta.requestId] = "fulfilled";
+      }
+    );
+});
+```
+   */
+  addMatcher<A>(
+    matcher: TypeGuard<A> | ((action: any) => boolean),
+    reducer: CaseReducer<State, A extends Action ? A : A & Action>,
+  ): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>
+
+  /**
+   * Adds a "default case" reducer that is executed if no case reducer and no matcher
+   * reducer was executed for this action.
+   * @param reducer - The fallback "default case" reducer function.
+   *
+   * @example
+```ts
+import { createReducer } from '@reduxjs/toolkit'
+const initialState = { otherActions: 0 }
+const reducer = createReducer(initialState, builder => {
+  builder
+    // .addCase(...)
+    // .addMatcher(...)
+    .addDefaultCase((state, action) => {
+      state.otherActions++
+    })
+})
+```
+   */
+  addDefaultCase(reducer: CaseReducer<State, Action>): {}
+}
+
+export function executeReducerBuilderCallback<S>(
+  builderCallback: (builder: ActionReducerMapBuilder<S>) => void,
+): [
+  CaseReducers<S, any>,
+  ActionMatcherDescriptionCollection<S>,
+  CaseReducer<S, Action> | undefined,
+] {
+  const actionsMap: CaseReducers<S, any> = {}
+  const actionMatchers: ActionMatcherDescriptionCollection<S> = []
+  let defaultCaseReducer: CaseReducer<S, Action> | undefined
+  const builder = {
+    addCase(
+      typeOrActionCreator: string | TypedActionCreator<any>,
+      reducer: CaseReducer<S>,
+    ) {
+      if (process.env.NODE_ENV !== 'production') {
+        /*
+         to keep the definition by the user in line with actual behavior,
+         we enforce `addCase` to always be called before calling `addMatcher`
+         as matching cases take precedence over matchers
+         */
+        if (actionMatchers.length > 0) {
+          throw new Error(
+            '`builder.addCase` should only be called before calling `builder.addMatcher`',
+          )
+        }
+        if (defaultCaseReducer) {
+          throw new Error(
+            '`builder.addCase` should only be called before calling `builder.addDefaultCase`',
+          )
+        }
+      }
+      const type =
+        typeof typeOrActionCreator === 'string'
+          ? typeOrActionCreator
+          : typeOrActionCreator.type
+      if (!type) {
+        throw new Error(
+          '`builder.addCase` cannot be called with an empty action type',
+        )
+      }
+      if (type in actionsMap) {
+        throw new Error(
+          '`builder.addCase` cannot be called with two reducers for the same action type ' +
+            `'${type}'`,
+        )
+      }
+      actionsMap[type] = reducer
+      return builder
+    },
+    addAsyncThunk<
+      Returned,
+      ThunkArg,
+      ThunkApiConfig extends AsyncThunkConfig = {},
+    >(
+      asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,
+      reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>,
+    ) {
+      if (process.env.NODE_ENV !== 'production') {
+        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case
+        if (defaultCaseReducer) {
+          throw new Error(
+            '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`',
+          )
+        }
+      }
+      if (reducers.pending)
+        actionsMap[asyncThunk.pending.type] = reducers.pending
+      if (reducers.rejected)
+        actionsMap[asyncThunk.rejected.type] = reducers.rejected
+      if (reducers.fulfilled)
+        actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled
+      if (reducers.settled)
+        actionMatchers.push({
+          matcher: asyncThunk.settled,
+          reducer: reducers.settled,
+        })
+      return builder
+    },
+    addMatcher<A>(
+      matcher: TypeGuard<A>,
+      reducer: CaseReducer<S, A extends Action ? A : A & Action>,
+    ) {
+      if (process.env.NODE_ENV !== 'production') {
+        if (defaultCaseReducer) {
+          throw new Error(
+            '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`',
+          )
+        }
+      }
+      actionMatchers.push({ matcher, reducer })
+      return builder
+    },
+    addDefaultCase(reducer: CaseReducer<S, Action>) {
+      if (process.env.NODE_ENV !== 'production') {
+        if (defaultCaseReducer) {
+          throw new Error('`builder.addDefaultCase` can only be called once')
+        }
+      }
+      defaultCaseReducer = reducer
+      return builder
+    },
+  }
+  builderCallback(builder)
+  return [actionsMap, actionMatchers, defaultCaseReducer]
+}
Index: node_modules/@reduxjs/toolkit/src/matchers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/matchers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/matchers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,365 @@
+import type {
+  ActionFromMatcher,
+  Matcher,
+  UnionToIntersection,
+} from './tsHelpers'
+import { hasMatchFunction } from './tsHelpers'
+import type {
+  AsyncThunk,
+  AsyncThunkFulfilledActionCreator,
+  AsyncThunkPendingActionCreator,
+  AsyncThunkRejectedActionCreator,
+} from './createAsyncThunk'
+
+/** @public */
+export type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> =
+  ActionFromMatcher<Matchers[number]>
+
+/** @public */
+export type ActionMatchingAllOf<Matchers extends Matcher<any>[]> =
+  UnionToIntersection<ActionMatchingAnyOf<Matchers>>
+
+const matches = (matcher: Matcher<any>, action: any) => {
+  if (hasMatchFunction(matcher)) {
+    return matcher.match(action)
+  } else {
+    return matcher(action)
+  }
+}
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches any one of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+export function isAnyOf<Matchers extends Matcher<any>[]>(
+  ...matchers: Matchers
+) {
+  return (action: any): action is ActionMatchingAnyOf<Matchers> => {
+    return matchers.some((matcher) => matches(matcher, action))
+  }
+}
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action matches all of the supplied type guards or action
+ * creators.
+ *
+ * @param matchers The type guards or action creators to match against.
+ *
+ * @public
+ */
+export function isAllOf<Matchers extends Matcher<any>[]>(
+  ...matchers: Matchers
+) {
+  return (action: any): action is ActionMatchingAllOf<Matchers> => {
+    return matchers.every((matcher) => matches(matcher, action))
+  }
+}
+
+/**
+ * @param action A redux action
+ * @param validStatus An array of valid meta.requestStatus values
+ *
+ * @internal
+ */
+export function hasExpectedRequestMetadata(
+  action: any,
+  validStatus: readonly string[],
+) {
+  if (!action || !action.meta) return false
+
+  const hasValidRequestId = typeof action.meta.requestId === 'string'
+  const hasValidRequestStatus =
+    validStatus.indexOf(action.meta.requestStatus) > -1
+
+  return hasValidRequestId && hasValidRequestStatus
+}
+
+function isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {
+  return (
+    typeof a[0] === 'function' &&
+    'pending' in a[0] &&
+    'fulfilled' in a[0] &&
+    'rejected' in a[0]
+  )
+}
+
+export type UnknownAsyncThunkPendingAction = ReturnType<
+  AsyncThunkPendingActionCreator<unknown>
+>
+
+export type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['pending']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is pending.
+ *
+ * @public
+ */
+export function isPending(): (
+  action: any,
+) => action is UnknownAsyncThunkPendingAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is pending.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isPending<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a pending thunk action
+ * @public
+ */
+export function isPending(action: any): action is UnknownAsyncThunkPendingAction
+export function isPending<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) => hasExpectedRequestMetadata(action, ['pending'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isPending()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending))
+}
+
+export type UnknownAsyncThunkRejectedAction = ReturnType<
+  AsyncThunkRejectedActionCreator<unknown, unknown>
+>
+
+export type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['rejected']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected.
+ *
+ * @public
+ */
+export function isRejected(): (
+  action: any,
+) => action is UnknownAsyncThunkRejectedAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isRejected<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a rejected thunk action
+ * @public
+ */
+export function isRejected(
+  action: any,
+): action is UnknownAsyncThunkRejectedAction
+export function isRejected<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) => hasExpectedRequestMetadata(action, ['rejected'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejected()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected))
+}
+
+export type UnknownAsyncThunkRejectedWithValueAction = ReturnType<
+  AsyncThunkRejectedActionCreator<unknown, unknown>
+>
+
+export type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['rejected']> &
+    (T extends AsyncThunk<any, any, { rejectValue: infer RejectedValue }>
+      ? { payload: RejectedValue }
+      : unknown)
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is rejected with value.
+ *
+ * @public
+ */
+export function isRejectedWithValue(): (
+  action: any,
+) => action is UnknownAsyncThunkRejectedAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is rejected with value.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isRejectedWithValue<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (
+  action: any,
+) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a rejected thunk action with value
+ * @public
+ */
+export function isRejectedWithValue(
+  action: any,
+): action is UnknownAsyncThunkRejectedAction
+export function isRejectedWithValue<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  const hasFlag = (action: any): action is any => {
+    return action && action.meta && action.meta.rejectedWithValue
+  }
+
+  if (asyncThunks.length === 0) {
+    return isAllOf(isRejected(...asyncThunks), hasFlag)
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isRejectedWithValue()(asyncThunks[0])
+  }
+
+  return isAllOf(isRejected(...asyncThunks), hasFlag)
+}
+
+export type UnknownAsyncThunkFulfilledAction = ReturnType<
+  AsyncThunkFulfilledActionCreator<unknown, unknown>
+>
+
+export type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> =
+  ActionFromMatcher<T['fulfilled']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator, and that
+ * the action is fulfilled.
+ *
+ * @public
+ */
+export function isFulfilled(): (
+  action: any,
+) => action is UnknownAsyncThunkFulfilledAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators,
+ * and that the action is fulfilled.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isFulfilled<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a fulfilled thunk action
+ * @public
+ */
+export function isFulfilled(
+  action: any,
+): action is UnknownAsyncThunkFulfilledAction
+export function isFulfilled<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isFulfilled()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled))
+}
+
+export type UnknownAsyncThunkAction =
+  | UnknownAsyncThunkPendingAction
+  | UnknownAsyncThunkRejectedAction
+  | UnknownAsyncThunkFulfilledAction
+
+export type AnyAsyncThunk = {
+  pending: { match: (action: any) => action is any }
+  fulfilled: { match: (action: any) => action is any }
+  rejected: { match: (action: any) => action is any }
+}
+
+export type ActionsFromAsyncThunk<T extends AnyAsyncThunk> =
+  | ActionFromMatcher<T['pending']>
+  | ActionFromMatcher<T['fulfilled']>
+  | ActionFromMatcher<T['rejected']>
+
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action was created by an async thunk action creator.
+ *
+ * @public
+ */
+export function isAsyncThunkAction(): (
+  action: any,
+) => action is UnknownAsyncThunkAction
+/**
+ * A higher-order function that returns a function that may be used to check
+ * whether an action belongs to one of the provided async thunk action creators.
+ *
+ * @param asyncThunks (optional) The async thunk action creators to match against.
+ *
+ * @public
+ */
+export function isAsyncThunkAction<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(
+  ...asyncThunks: AsyncThunks
+): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>
+/**
+ * Tests if `action` is a thunk action
+ * @public
+ */
+export function isAsyncThunkAction(
+  action: any,
+): action is UnknownAsyncThunkAction
+export function isAsyncThunkAction<
+  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],
+>(...asyncThunks: AsyncThunks | [any]) {
+  if (asyncThunks.length === 0) {
+    return (action: any) =>
+      hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected'])
+  }
+
+  if (!isAsyncThunkArray(asyncThunks)) {
+    return isAsyncThunkAction()(asyncThunks[0])
+  }
+
+  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]))
+}
Index: node_modules/@reduxjs/toolkit/src/nanoid.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/nanoid.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/nanoid.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,20 @@
+// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js
+// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped
+// optimize the gzip compression for this alphabet.
+let urlAlphabet =
+  'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
+
+/**
+ *
+ * @public
+ */
+export let nanoid = (size = 21) => {
+  let id = ''
+  // A compact alternative for `for (var i = 0; i < step; i++)`.
+  let i = size
+  while (i--) {
+    // `| 0` is more compact and faster than `Math.floor()`.
+    id += urlAlphabet[(Math.random() * 64) | 0]
+  }
+  return id
+}
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
+}
Index: node_modules/@reduxjs/toolkit/src/react/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,7 @@
+// 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 * from '@reduxjs/toolkit'
+
+export { createDynamicMiddleware } from '../dynamicMiddleware/react'
+export type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index'
Index: node_modules/@reduxjs/toolkit/src/reduxImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/reduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/reduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+export {
+  createStore,
+  combineReducers,
+  applyMiddleware,
+  compose,
+  isPlainObject,
+  isAction,
+} from 'redux'
Index: node_modules/@reduxjs/toolkit/src/reselectImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/reselectImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/reselectImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+export { createSelectorCreator, weakMapMemoize } from 'reselect'
Index: node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/serializableStateInvariantMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,285 @@
+import type { Middleware } from 'redux'
+import { isAction, isPlainObject } from './reduxImports'
+import { getTimeMeasureUtils } from './utils'
+
+/**
+ * Returns true if the passed value is "plain", i.e. a value that is either
+ * directly JSON-serializable (boolean, number, string, array, plain object)
+ * or `undefined`.
+ *
+ * @param val The value to check.
+ *
+ * @public
+ */
+export function isPlain(val: any) {
+  const type = typeof val
+  return (
+    val == null ||
+    type === 'string' ||
+    type === 'boolean' ||
+    type === 'number' ||
+    Array.isArray(val) ||
+    isPlainObject(val)
+  )
+}
+
+interface NonSerializableValue {
+  keyPath: string
+  value: unknown
+}
+
+export type IgnorePaths = readonly (string | RegExp)[]
+
+/**
+ * @public
+ */
+export function findNonSerializableValue(
+  value: unknown,
+  path: string = '',
+  isSerializable: (value: unknown) => boolean = isPlain,
+  getEntries?: (value: unknown) => [string, any][],
+  ignoredPaths: IgnorePaths = [],
+  cache?: WeakSet<object>,
+): NonSerializableValue | false {
+  let foundNestedSerializable: NonSerializableValue | false
+
+  if (!isSerializable(value)) {
+    return {
+      keyPath: path || '<root>',
+      value: value,
+    }
+  }
+
+  if (typeof value !== 'object' || value === null) {
+    return false
+  }
+
+  if (cache?.has(value)) return false
+
+  const entries = getEntries != null ? getEntries(value) : Object.entries(value)
+
+  const hasIgnoredPaths = ignoredPaths.length > 0
+
+  for (const [key, nestedValue] of entries) {
+    const nestedPath = path ? path + '.' + key : key
+
+    if (hasIgnoredPaths) {
+      const hasMatches = ignoredPaths.some((ignored) => {
+        if (ignored instanceof RegExp) {
+          return ignored.test(nestedPath)
+        }
+        return nestedPath === ignored
+      })
+      if (hasMatches) {
+        continue
+      }
+    }
+
+    if (!isSerializable(nestedValue)) {
+      return {
+        keyPath: nestedPath,
+        value: nestedValue,
+      }
+    }
+
+    if (typeof nestedValue === 'object') {
+      foundNestedSerializable = findNonSerializableValue(
+        nestedValue,
+        nestedPath,
+        isSerializable,
+        getEntries,
+        ignoredPaths,
+        cache,
+      )
+
+      if (foundNestedSerializable) {
+        return foundNestedSerializable
+      }
+    }
+  }
+
+  if (cache && isNestedFrozen(value)) cache.add(value)
+
+  return false
+}
+
+export function isNestedFrozen(value: object) {
+  if (!Object.isFrozen(value)) return false
+
+  for (const nestedValue of Object.values(value)) {
+    if (typeof nestedValue !== 'object' || nestedValue === null) continue
+
+    if (!isNestedFrozen(nestedValue)) return false
+  }
+
+  return true
+}
+
+/**
+ * Options for `createSerializableStateInvariantMiddleware()`.
+ *
+ * @public
+ */
+export interface SerializableStateInvariantMiddlewareOptions {
+  /**
+   * The function to check if a value is considered serializable. This
+   * function is applied recursively to every value contained in the
+   * state. Defaults to `isPlain()`.
+   */
+  isSerializable?: (value: any) => boolean
+  /**
+   * The function that will be used to retrieve entries from each
+   * value.  If unspecified, `Object.entries` will be used. Defaults
+   * to `undefined`.
+   */
+  getEntries?: (value: any) => [string, any][]
+
+  /**
+   * An array of action types to ignore when checking for serializability.
+   * Defaults to []
+   */
+  ignoredActions?: string[]
+
+  /**
+   * An array of dot-separated path strings or regular expressions to ignore
+   * when checking for serializability, Defaults to
+   * ['meta.arg', 'meta.baseQueryMeta']
+   */
+  ignoredActionPaths?: (string | RegExp)[]
+
+  /**
+   * An array of dot-separated path strings or regular expressions to ignore
+   * when checking for serializability, Defaults to []
+   */
+  ignoredPaths?: (string | RegExp)[]
+  /**
+   * Execution time warning threshold. If the middleware takes longer
+   * than `warnAfter` ms, a warning will be displayed in the console.
+   * Defaults to 32ms.
+   */
+  warnAfter?: number
+
+  /**
+   * Opt out of checking state. When set to `true`, other state-related params will be ignored.
+   */
+  ignoreState?: boolean
+
+  /**
+   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.
+   */
+  ignoreActions?: boolean
+
+  /**
+   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.
+   * The cache is automatically disabled if no browser support for WeakSet is present.
+   */
+  disableCache?: boolean
+}
+
+/**
+ * Creates a middleware that, after every state change, checks if the new
+ * state is serializable. If a non-serializable value is found within the
+ * state, an error is printed to the console.
+ *
+ * @param options Middleware options.
+ *
+ * @public
+ */
+export function createSerializableStateInvariantMiddleware(
+  options: SerializableStateInvariantMiddlewareOptions = {},
+): Middleware {
+  if (process.env.NODE_ENV === 'production') {
+    return () => (next) => (action) => next(action)
+  } else {
+    const {
+      isSerializable = isPlain,
+      getEntries,
+      ignoredActions = [],
+      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],
+      ignoredPaths = [],
+      warnAfter = 32,
+      ignoreState = false,
+      ignoreActions = false,
+      disableCache = false,
+    } = options
+
+    const cache: WeakSet<object> | undefined =
+      !disableCache && WeakSet ? new WeakSet() : undefined
+
+    return (storeAPI) => (next) => (action) => {
+      if (!isAction(action)) {
+        return next(action)
+      }
+
+      const result = next(action)
+
+      const measureUtils = getTimeMeasureUtils(
+        warnAfter,
+        'SerializableStateInvariantMiddleware',
+      )
+
+      if (
+        !ignoreActions &&
+        !(
+          ignoredActions.length &&
+          ignoredActions.indexOf(action.type as any) !== -1
+        )
+      ) {
+        measureUtils.measureTime(() => {
+          const foundActionNonSerializableValue = findNonSerializableValue(
+            action,
+            '',
+            isSerializable,
+            getEntries,
+            ignoredActionPaths,
+            cache,
+          )
+
+          if (foundActionNonSerializableValue) {
+            const { keyPath, value } = foundActionNonSerializableValue
+
+            console.error(
+              `A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`,
+              value,
+              '\nTake a look at the logic that dispatched this action: ',
+              action,
+              '\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)',
+              '\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)',
+            )
+          }
+        })
+      }
+
+      if (!ignoreState) {
+        measureUtils.measureTime(() => {
+          const state = storeAPI.getState()
+
+          const foundStateNonSerializableValue = findNonSerializableValue(
+            state,
+            '',
+            isSerializable,
+            getEntries,
+            ignoredPaths,
+            cache,
+          )
+
+          if (foundStateNonSerializableValue) {
+            const { keyPath, value } = foundStateNonSerializableValue
+
+            console.error(
+              `A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`,
+              value,
+              `
+Take a look at the reducer(s) handling this action type: ${action.type}.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+            )
+          }
+        })
+
+        measureUtils.warnIfExceeded()
+      }
+
+      return result
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/tests/Tuple.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/Tuple.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/Tuple.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,83 @@
+import { Tuple } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('compatibility is checked between described types', () => {
+    const stringTuple = new Tuple('')
+
+    expectTypeOf(stringTuple).toEqualTypeOf<Tuple<[string]>>()
+
+    expectTypeOf(stringTuple).toMatchTypeOf<Tuple<string[]>>()
+
+    expectTypeOf(stringTuple).not.toMatchTypeOf<Tuple<[string, string]>>()
+
+    const numberTuple = new Tuple(0, 1)
+
+    expectTypeOf(numberTuple).not.toMatchTypeOf<Tuple<string[]>>()
+  })
+
+  test('concat is inferred properly', () => {
+    const singleString = new Tuple('')
+
+    expectTypeOf(singleString).toEqualTypeOf<Tuple<[string]>>()
+
+    expectTypeOf(singleString.concat('')).toEqualTypeOf<
+      Tuple<[string, string]>
+    >()
+
+    expectTypeOf(singleString.concat([''] as const)).toMatchTypeOf<
+      Tuple<[string, string]>
+    >()
+  })
+
+  test('prepend is inferred properly', () => {
+    const singleString = new Tuple('')
+
+    expectTypeOf(singleString).toEqualTypeOf<Tuple<[string]>>()
+
+    expectTypeOf(singleString.prepend('')).toEqualTypeOf<
+      Tuple<[string, string]>
+    >()
+
+    expectTypeOf(singleString.prepend([''] as const)).toMatchTypeOf<
+      Tuple<[string, string]>
+    >()
+  })
+
+  test('push must match existing items', () => {
+    const stringTuple = new Tuple('')
+
+    expectTypeOf(stringTuple.push).toBeCallableWith('')
+
+    expectTypeOf(stringTuple.push).parameter(0).not.toBeNumber()
+  })
+
+  test('Tuples can be combined', () => {
+    const stringTuple = new Tuple('')
+
+    const numberTuple = new Tuple(0, 1)
+
+    expectTypeOf(stringTuple.concat(numberTuple)).toEqualTypeOf<
+      Tuple<[string, number, number]>
+    >()
+
+    expectTypeOf(stringTuple.prepend(numberTuple)).toEqualTypeOf<
+      Tuple<[number, number, string]>
+    >()
+
+    expectTypeOf(numberTuple.concat(stringTuple)).toEqualTypeOf<
+      Tuple<[number, number, string]>
+    >()
+
+    expectTypeOf(numberTuple.prepend(stringTuple)).toEqualTypeOf<
+      Tuple<[string, number, number]>
+    >()
+
+    expectTypeOf(stringTuple.prepend(numberTuple)).not.toMatchTypeOf<
+      Tuple<[string, number, number]>
+    >()
+
+    expectTypeOf(stringTuple.concat(numberTuple)).not.toMatchTypeOf<
+      Tuple<[number, number, string]>
+    >()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,61 @@
+import type { ActionCreatorInvariantMiddlewareOptions } from '@internal/actionCreatorInvariantMiddleware'
+import { getMessage } from '@internal/actionCreatorInvariantMiddleware'
+import { createActionCreatorInvariantMiddleware } from '@internal/actionCreatorInvariantMiddleware'
+import type { MiddlewareAPI } from '@reduxjs/toolkit'
+import { createAction } from '@reduxjs/toolkit'
+
+describe('createActionCreatorInvariantMiddleware', () => {
+  const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+  afterEach(() => {
+    consoleSpy.mockClear()
+  })
+  afterAll(() => {
+    consoleSpy.mockRestore()
+  })
+
+  const dummyAction = createAction('aSlice/anAction')
+
+  it('sends the action through the middleware chain', () => {
+    const next = vi.fn()
+    const dispatch = createActionCreatorInvariantMiddleware()(
+      {} as MiddlewareAPI,
+    )(next)
+    dispatch({ type: 'SOME_ACTION' })
+
+    expect(next).toHaveBeenCalledWith({
+      type: 'SOME_ACTION',
+    })
+  })
+
+  const makeActionTester = (
+    options?: ActionCreatorInvariantMiddlewareOptions,
+  ) =>
+    createActionCreatorInvariantMiddleware(options)({} as MiddlewareAPI)(
+      (action) => action,
+    )
+
+  it('logs a warning to console if an action creator is mistakenly dispatched', () => {
+    const testAction = makeActionTester()
+
+    testAction(dummyAction())
+
+    expect(consoleSpy).not.toHaveBeenCalled()
+
+    testAction(dummyAction)
+
+    expect(consoleSpy).toHaveBeenLastCalledWith(getMessage(dummyAction.type))
+  })
+
+  it('allows passing a custom predicate', () => {
+    let predicateCalled = false
+    const testAction = makeActionTester({
+      isActionCreator(action): action is Function {
+        predicateCalled = true
+        return false
+      },
+    })
+    testAction(dummyAction())
+    expect(predicateCalled).toBe(true)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/autoBatchEnhancer.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/autoBatchEnhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/autoBatchEnhancer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,208 @@
+import { configureStore } from '../configureStore'
+import { createSlice } from '../createSlice'
+import type { AutoBatchOptions } from '../autoBatchEnhancer'
+import { autoBatchEnhancer, prepareAutoBatched } from '../autoBatchEnhancer'
+import { delay } from '../utils'
+import { debounce } from 'lodash'
+
+interface CounterState {
+  value: number
+}
+
+const counterSlice = createSlice({
+  name: 'counter',
+  initialState: { value: 0 } as CounterState,
+  reducers: {
+    incrementBatched: {
+      // Batched, low-priority
+      reducer(state) {
+        state.value += 1
+      },
+      prepare: prepareAutoBatched<void>(),
+    },
+    // Not batched, normal priority
+    decrementUnbatched(state) {
+      state.value -= 1
+    },
+  },
+})
+const { incrementBatched, decrementUnbatched } = counterSlice.actions
+
+const makeStore = (autoBatchOptions?: AutoBatchOptions) => {
+  return configureStore({
+    reducer: counterSlice.reducer,
+    enhancers: (getDefaultEnhancers) =>
+      getDefaultEnhancers({
+        autoBatch: autoBatchOptions,
+      }),
+  })
+}
+
+let store: ReturnType<typeof makeStore>
+
+let subscriptionNotifications = 0
+
+const cases: AutoBatchOptions[] = [
+  { type: 'tick' },
+  { type: 'raf' },
+  { type: 'timer', timeout: 0 },
+  { type: 'timer', timeout: 10 },
+  { type: 'timer', timeout: 20 },
+  {
+    type: 'callback',
+    queueNotification: debounce((notify: () => void) => {
+      notify()
+    }, 5),
+  },
+]
+
+describe.each(cases)('autoBatchEnhancer: %j', (autoBatchOptions) => {
+  beforeEach(() => {
+    subscriptionNotifications = 0
+    store = makeStore(autoBatchOptions)
+
+    store.subscribe(() => {
+      subscriptionNotifications++
+    })
+  })
+  test('Does not alter normal subscription notification behavior', async () => {
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(1)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(2)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(3)
+    store.dispatch(decrementUnbatched())
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(4)
+  })
+
+  test('Only notifies once if several batched actions are dispatched in a row', async () => {
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(1)
+  })
+
+  test('Notifies immediately if a non-batched action is dispatched', async () => {
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(1)
+    store.dispatch(incrementBatched())
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(2)
+  })
+
+  test('Does not notify at end of tick if last action was normal priority', async () => {
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(incrementBatched())
+    expect(subscriptionNotifications).toBe(0)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(1)
+    store.dispatch(incrementBatched())
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(2)
+    store.dispatch(decrementUnbatched())
+    expect(subscriptionNotifications).toBe(3)
+
+    await delay(25)
+
+    expect(subscriptionNotifications).toBe(3)
+  })
+})
+
+describe.each(cases)(
+  'autoBatchEnhancer with fake timers: %j',
+  (autoBatchOptions) => {
+    beforeAll(() => {
+      vitest.useFakeTimers({
+        toFake: ['setTimeout', 'queueMicrotask', 'requestAnimationFrame'],
+      })
+    })
+    afterAll(() => {
+      vitest.useRealTimers()
+    })
+    beforeEach(() => {
+      subscriptionNotifications = 0
+      store = makeStore(autoBatchOptions)
+
+      store.subscribe(() => {
+        subscriptionNotifications++
+      })
+    })
+    test('Does not alter normal subscription notification behavior', () => {
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(1)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(2)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(3)
+      store.dispatch(decrementUnbatched())
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(4)
+    })
+
+    test('Only notifies once if several batched actions are dispatched in a row', () => {
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(1)
+    })
+
+    test('Notifies immediately if a non-batched action is dispatched', () => {
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(1)
+      store.dispatch(incrementBatched())
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(2)
+    })
+
+    test('Does not notify at end of tick if last action was normal priority', () => {
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(incrementBatched())
+      expect(subscriptionNotifications).toBe(0)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(1)
+      store.dispatch(incrementBatched())
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(2)
+      store.dispatch(decrementUnbatched())
+      expect(subscriptionNotifications).toBe(3)
+
+      vitest.runAllTimers()
+
+      expect(subscriptionNotifications).toBe(3)
+    })
+  },
+)
Index: node_modules/@reduxjs/toolkit/src/tests/combineSlices.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/combineSlices.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/combineSlices.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,284 @@
+import type {
+  Action,
+  Reducer,
+  Slice,
+  WithSlice,
+  WithSlicePreloadedState,
+} from '@reduxjs/toolkit'
+import { combineSlices } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+declare const stringSlice: Slice<string, {}, 'string'>
+
+declare const numberSlice: Slice<number, {}, 'number'>
+
+declare const booleanReducer: Reducer<boolean>
+
+declare const mixedReducer: Reducer<string, Action, number>
+
+declare const mixedSliceLike: {
+  reducerPath: 'mixedSlice'
+  reducer: typeof mixedReducer
+}
+
+const exampleApi = createApi({
+  baseQuery: fetchBaseQuery(),
+  endpoints: (build) => ({
+    getThing: build.query({
+      query: () => '',
+    }),
+  }),
+})
+
+type ExampleApiState = ReturnType<typeof exampleApi.reducer>
+
+describe('type tests', () => {
+  test('combineSlices correctly combines static state', () => {
+    const rootReducer = combineSlices(
+      stringSlice,
+      numberSlice,
+      exampleApi,
+      {
+        boolean: booleanReducer,
+        mixed: mixedReducer,
+      },
+      mixedSliceLike,
+    )
+
+    expectTypeOf(rootReducer(undefined, { type: '' })).toEqualTypeOf<{
+      string: string
+      number: number
+      boolean: boolean
+      api: ExampleApiState
+      mixed: string
+      mixedSlice: string
+    }>()
+
+    // test for correct preloaded state handling
+    expectTypeOf(rootReducer).toBeCallableWith(
+      { mixed: 9, mixedSlice: 9 },
+      { type: '' },
+    )
+  })
+
+  test('combineSlices allows passing no initial reducers', () => {
+    const rootReducer = combineSlices()
+
+    expectTypeOf(rootReducer(undefined, { type: '' })).toEqualTypeOf<{}>()
+
+    const declaredLazy =
+      combineSlices().withLazyLoadedSlices<WithSlice<typeof numberSlice>>()
+
+    expectTypeOf(declaredLazy(undefined, { type: '' })).toEqualTypeOf<{
+      number?: number
+    }>()
+  })
+
+  test('withLazyLoadedSlices adds partial to state', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> & WithSlice<typeof exampleApi>
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).number).toEqualTypeOf<
+      number | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).api).toEqualTypeOf<
+      ExampleApiState | undefined
+    >()
+  })
+
+  test('inject marks injected keys as required', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> &
+        WithSlice<typeof exampleApi> & { boolean: boolean } & WithSlice<
+          typeof mixedSliceLike
+        > &
+        WithSlice<{
+          reducerPath: 'mixedReducer'
+          reducer: typeof mixedReducer
+        }>,
+      WithSlicePreloadedState<typeof numberSlice> &
+        WithSlicePreloadedState<typeof exampleApi> & {
+          boolean: boolean
+        } & WithSlicePreloadedState<typeof mixedSliceLike> &
+        WithSlicePreloadedState<{
+          reducerPath: 'mixedReducer'
+          reducer: typeof mixedReducer
+        }>
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).number).toEqualTypeOf<
+      number | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).boolean).toEqualTypeOf<
+      boolean | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).api).toEqualTypeOf<
+      ExampleApiState | undefined
+    >()
+
+    expectTypeOf(rootReducer(undefined, { type: '' }).mixedSlice).toEqualTypeOf<
+      string | undefined
+    >()
+
+    expectTypeOf(
+      rootReducer(undefined, { type: '' }).mixedReducer,
+    ).toEqualTypeOf<string | undefined>()
+
+    const withNumber = rootReducer.inject(numberSlice)
+
+    expectTypeOf(withNumber(undefined, { type: '' }).number).toBeNumber()
+
+    const withBool = rootReducer.inject({
+      reducerPath: 'boolean' as const,
+      reducer: booleanReducer,
+    })
+
+    expectTypeOf(withBool(undefined, { type: '' }).boolean).toBeBoolean()
+
+    const withApi = rootReducer.inject(exampleApi)
+
+    expectTypeOf(
+      withApi(undefined, { type: '' }).api,
+    ).toEqualTypeOf<ExampleApiState>()
+
+    const withMixedSlice = rootReducer.inject(mixedSliceLike)
+
+    expectTypeOf(
+      withMixedSlice(undefined, { type: '' }).mixedSlice,
+    ).toBeString()
+
+    const withMixedReducer = rootReducer.inject({
+      reducerPath: 'mixedReducer',
+      reducer: mixedReducer,
+    })
+
+    expectTypeOf(
+      withMixedReducer(undefined, { type: '' }).mixedReducer,
+    ).toBeString()
+  })
+
+  test('selector() allows defining selectors with injected reducers defined', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> & { boolean: boolean }
+    >()
+
+    type RootState = ReturnType<typeof rootReducer>
+
+    const withoutInjection = rootReducer.selector(
+      (state: RootState) => state.number,
+    )
+
+    expectTypeOf(
+      withoutInjection(rootReducer(undefined, { type: '' })),
+    ).toEqualTypeOf<number | undefined>()
+
+    const withInjection = rootReducer
+      .inject(numberSlice)
+      .selector((state) => state.number)
+
+    expectTypeOf(
+      withInjection(rootReducer(undefined, { type: '' })),
+    ).toBeNumber()
+  })
+
+  test('selector() passes arguments through', () => {
+    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+      WithSlice<typeof numberSlice> & { boolean: boolean }
+    >()
+
+    const selector = rootReducer
+      .inject(numberSlice)
+      .selector((state, num: number) => state.number)
+
+    const state = rootReducer(undefined, { type: '' })
+
+    expectTypeOf(selector).toBeCallableWith(state, 0)
+
+    // required argument
+    expectTypeOf(selector).parameters.not.toMatchTypeOf([state])
+
+    // number not string
+    expectTypeOf(selector).parameters.not.toMatchTypeOf([state, ''])
+  })
+
+  test('nested calls inferred correctly', () => {
+    const innerReducer =
+      combineSlices(stringSlice).withLazyLoadedSlices<
+        WithSlice<typeof numberSlice>
+      >()
+
+    const innerSelector = innerReducer.inject(numberSlice).selector(
+      (state) => state.number,
+      (rootState: RootState) => rootState.inner,
+    )
+
+    const outerReducer = combineSlices({ inner: innerReducer })
+
+    type RootState = ReturnType<typeof outerReducer>
+
+    expectTypeOf(outerReducer(undefined, { type: '' })).toMatchTypeOf<{
+      inner: { string: string }
+    }>()
+
+    expectTypeOf(
+      innerSelector(outerReducer(undefined, { type: '' })),
+    ).toBeNumber()
+  })
+
+  test('selector errors if selectorFn and selectState are mismatched', () => {
+    const combinedReducer =
+      combineSlices(stringSlice).withLazyLoadedSlices<
+        WithSlice<typeof numberSlice>
+      >()
+
+    const outerReducer = combineSlices({ inner: combinedReducer })
+
+    type RootState = ReturnType<typeof outerReducer>
+
+    combinedReducer.selector(
+      (state) => state.number,
+      // @ts-expect-error wrong state returned
+      (rootState: RootState) => rootState.inner.number,
+    )
+
+    combinedReducer.selector(
+      (state, num: number) => state.number,
+      // @ts-expect-error wrong arguments
+      (rootState: RootState, str: string) => rootState.inner,
+    )
+
+    combinedReducer.selector(
+      (state, num: number) => state.number,
+      (rootState: RootState) => rootState.inner,
+    )
+
+    // TODO: see if there's a way of making this work
+    // probably a rare case so not the end of the world if not
+    combinedReducer.selector(
+      (state) => state.number,
+      // @ts-ignore
+      (rootState: RootState, num: number) => rootState.inner,
+    )
+  })
+
+  test('correct type of state is inferred when not declared via `withLazyLoadedSlices`', () => {
+    // Related to https://github.com/reduxjs/redux-toolkit/issues/4171
+
+    const combinedReducer = combineSlices(stringSlice)
+
+    const withNumber = combinedReducer.inject(numberSlice)
+
+    expectTypeOf(withNumber).returns.toEqualTypeOf<{
+      string: string
+      number: number
+    }>()
+
+    expectTypeOf(
+      withNumber(undefined, { type: '' }).number,
+    ).toMatchTypeOf<number>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/combineSlices.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/combineSlices.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/combineSlices.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,215 @@
+import type { WithSlice } from '@reduxjs/toolkit'
+import {
+  combineSlices,
+  createAction,
+  createReducer,
+  createSlice,
+} from '@reduxjs/toolkit'
+
+const dummyAction = createAction<void>('dummy')
+
+const stringSlice = createSlice({
+  name: 'string',
+  initialState: '',
+  reducers: {},
+})
+
+const numberSlice = createSlice({
+  name: 'number',
+  initialState: 0,
+  reducers: {},
+})
+
+const booleanReducer = createReducer(false, () => {})
+
+const counterReducer = createSlice({
+  name: 'counter',
+  initialState: () => ({ value: 0 }),
+  reducers: {},
+})
+
+// mimic - we can't use RTKQ here directly
+const api = {
+  reducerPath: 'api' as const,
+  reducer: createReducer(
+    {
+      queries: {},
+      mutations: {},
+      provided: {},
+      subscriptions: {},
+      config: {
+        reducerPath: 'api',
+        invalidationBehavior: 'delayed',
+        online: false,
+        focused: false,
+        keepUnusedDataFor: 60,
+        middlewareRegistered: false,
+        refetchOnMountOrArgChange: false,
+        refetchOnReconnect: false,
+        refetchOnFocus: false,
+      },
+    },
+    () => {},
+  ),
+}
+
+describe('combineSlices', () => {
+  it('calls combineReducers to combine static slices/reducers', () => {
+    const combinedReducer = combineSlices(
+      stringSlice,
+      {
+        num: numberSlice.reducer,
+        boolean: booleanReducer,
+      },
+      api,
+    )
+    expect(combinedReducer(undefined, dummyAction())).toEqual({
+      string: stringSlice.getInitialState(),
+      num: numberSlice.getInitialState(),
+      boolean: booleanReducer.getInitialState(),
+      api: api.reducer.getInitialState(),
+    })
+  })
+  it('allows passing no initial reducers', () => {
+    const combinedReducer = combineSlices()
+
+    const result = combinedReducer(undefined, dummyAction())
+
+    expect(result).toEqual({})
+
+    // no-op if we have no reducers yet
+    expect(combinedReducer(result, dummyAction())).toBe(result)
+  })
+  describe('injects', () => {
+    beforeEach(() => {
+      vi.stubEnv('NODE_ENV', 'development')
+
+      return vi.unstubAllEnvs
+    })
+
+    it('injects slice', () => {
+      const combinedReducer =
+        combineSlices(stringSlice).withLazyLoadedSlices<
+          WithSlice<typeof numberSlice>
+        >()
+
+      expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)
+
+      const injectedReducer = combinedReducer.inject(numberSlice)
+
+      expect(injectedReducer(undefined, dummyAction()).number).toBe(
+        numberSlice.getInitialState(),
+      )
+    })
+    it('logs error when same name is used for different reducers', () => {
+      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+      const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<{
+        boolean: boolean
+      }>()
+
+      combinedReducer.inject({
+        reducerPath: 'boolean' as const,
+        reducer: booleanReducer,
+      })
+
+      combinedReducer.inject({
+        reducerPath: 'boolean' as const,
+        reducer: booleanReducer,
+      })
+
+      expect(consoleSpy).not.toHaveBeenCalled()
+
+      combinedReducer.inject({
+        reducerPath: 'boolean' as const,
+        // @ts-expect-error wrong reducer
+        reducer: stringSlice.reducer,
+      })
+
+      expect(consoleSpy).toHaveBeenCalledWith(
+        `called \`inject\` to override already-existing reducer boolean without specifying \`overrideExisting: true\``,
+      )
+      consoleSpy.mockRestore()
+    })
+    it('allows replacement of reducers if overrideExisting is true', () => {
+      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+      const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<
+        WithSlice<typeof numberSlice> &
+          WithSlice<typeof api> & { boolean: boolean }
+      >()
+
+      combinedReducer.inject(numberSlice)
+
+      combinedReducer.inject(
+        { reducerPath: 'number' as const, reducer: () => 0 },
+        { overrideExisting: true },
+      )
+
+      expect(consoleSpy).not.toHaveBeenCalled()
+    })
+  })
+  describe('selector', () => {
+    const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<{
+      boolean: boolean
+      counter: { value: number }
+    }>()
+
+    const uninjectedState = combinedReducer(undefined, dummyAction())
+
+    const injectedReducer = combinedReducer.inject({
+      reducerPath: 'boolean' as const,
+      reducer: booleanReducer,
+    })
+
+    it('ensures state is defined in selector even if action has not been dispatched', () => {
+      expect(uninjectedState.boolean).toBe(undefined)
+
+      const selectBoolean = injectedReducer.selector((state) => state.boolean)
+
+      expect(selectBoolean(uninjectedState)).toBe(
+        booleanReducer.getInitialState(),
+      )
+    })
+    it('exposes original to allow for logging', () => {
+      const selectBoolean = injectedReducer.selector(
+        (state) => injectedReducer.selector.original(state).boolean,
+      )
+      expect(selectBoolean(uninjectedState)).toBe(undefined)
+    })
+    it('throws if original is called on something other than state proxy', () => {
+      expect(() => injectedReducer.selector.original({} as any)).toThrow(
+        'original must be used on state Proxy',
+      )
+    })
+    it('allows passing a selectState selector, to handle nested state', () => {
+      const wrappedReducer = combineSlices({
+        inner: combinedReducer,
+      })
+
+      type RootState = ReturnType<typeof wrappedReducer>
+
+      const selector = injectedReducer.selector(
+        (state) => state.boolean,
+        (rootState: RootState) => rootState.inner,
+      )
+
+      expect(selector(wrappedReducer(undefined, dummyAction()))).toBe(
+        booleanReducer.getInitialState(),
+      )
+    })
+    it('caches initial state', () => {
+      const beforeInject = combinedReducer(undefined, dummyAction())
+      const injectedReducer = combinedReducer.inject(counterReducer)
+      const selectCounter = injectedReducer.selector((state) => state.counter)
+      const counter = selectCounter(beforeInject)
+      expect(counter).toBe(selectCounter(beforeInject))
+
+      injectedReducer.inject(
+        { reducerPath: 'counter', reducer: () => ({ value: 0 }) },
+        { overrideExisting: true },
+      )
+      const counter2 = selectCounter(beforeInject)
+      expect(counter2).not.toBe(counter)
+      expect(counter2).toBe(selectCounter(beforeInject))
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/combinedTest.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/combinedTest.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/combinedTest.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,133 @@
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  createAsyncThunk,
+  createAction,
+  createSlice,
+  configureStore,
+  createEntityAdapter,
+} from '@reduxjs/toolkit'
+import type { EntityAdapter } from '@internal/entities/models'
+import type { BookModel } from '@internal/entities/tests/fixtures/book'
+
+describe('Combined entity slice', () => {
+  let adapter: EntityAdapter<BookModel, string>
+
+  beforeEach(() => {
+    adapter = createEntityAdapter({
+      selectId: (book: BookModel) => book.id,
+      sortComparer: (a, b) => a.title.localeCompare(b.title),
+    })
+  })
+
+  it('Entity and async features all works together', async () => {
+    const upsertBook = createAction<BookModel>('otherBooks/upsert')
+
+    type BooksState = ReturnType<typeof adapter.getInitialState> & {
+      loading: 'initial' | 'pending' | 'finished' | 'failed'
+      lastRequestId: string | null
+    }
+
+    const initialState: BooksState = adapter.getInitialState({
+      loading: 'initial',
+      lastRequestId: null,
+    })
+
+    const fakeBooks: BookModel[] = [
+      { id: 'b', title: 'Second' },
+      { id: 'a', title: 'First' },
+    ]
+
+    const fetchBooksTAC = createAsyncThunk<
+      BookModel[],
+      void,
+      {
+        state: { books: BooksState }
+      }
+    >(
+      'books/fetch',
+      async (arg, { getState, dispatch, extra, requestId, signal }) => {
+        const state = getState()
+        return fakeBooks
+      },
+    )
+
+    const booksSlice = createSlice({
+      name: 'books',
+      initialState,
+      reducers: {
+        addOne: adapter.addOne,
+        removeOne(state, action: PayloadAction<string>) {
+          const sizeBefore = state.ids.length
+          // Originally, having nested `produce` calls don't mutate `state` here as I would have expected.
+          // (note that `state` here is actually an Immer Draft<S>, from `createReducer`)
+          // One woarkound was to return the new plain result value instead
+          // See https://github.com/immerjs/immer/issues/533
+          // However, after tweaking `createStateOperator` to check if the argument is a draft,
+          // we can just treat the operator as strictly mutating, without returning a result,
+          // and the result should be correct.
+          const result = adapter.removeOne(state, action)
+
+          const sizeAfter = state.ids.length
+          if (sizeBefore > 0) {
+            expect(sizeAfter).toBe(sizeBefore - 1)
+          }
+
+          //Deliberately _don't_ return result
+        },
+      },
+      extraReducers: (builder) => {
+        builder.addCase(upsertBook, (state, action) => {
+          return adapter.upsertOne(state, action)
+        })
+        builder.addCase(fetchBooksTAC.pending, (state, action) => {
+          state.loading = 'pending'
+          state.lastRequestId = action.meta.requestId
+        })
+        builder.addCase(fetchBooksTAC.fulfilled, (state, action) => {
+          if (
+            state.loading === 'pending' &&
+            action.meta.requestId === state.lastRequestId
+          ) {
+            adapter.setAll(state, action.payload)
+            state.loading = 'finished'
+            state.lastRequestId = null
+          }
+        })
+      },
+    })
+
+    const { addOne, removeOne } = booksSlice.actions
+    const { reducer } = booksSlice
+
+    const store = configureStore({
+      reducer: {
+        books: reducer,
+      },
+    })
+
+    await store.dispatch(fetchBooksTAC())
+
+    const { books: booksAfterLoaded } = store.getState()
+    // Sorted, so "First" goes first
+    expect(booksAfterLoaded.ids).toEqual(['a', 'b'])
+    expect(booksAfterLoaded.lastRequestId).toBe(null)
+    expect(booksAfterLoaded.loading).toBe('finished')
+
+    store.dispatch(addOne({ id: 'd', title: 'Remove Me' }))
+    store.dispatch(removeOne('d'))
+
+    store.dispatch(addOne({ id: 'c', title: 'Middle' }))
+
+    const { books: booksAfterAddOne } = store.getState()
+
+    // Sorted, so "Middle" goes in the middle
+    expect(booksAfterAddOne.ids).toEqual(['a', 'c', 'b'])
+
+    store.dispatch(upsertBook({ id: 'c', title: 'Zeroth' }))
+
+    const { books: booksAfterUpsert } = store.getState()
+
+    // Sorted, so "Zeroth" goes last
+    expect(booksAfterUpsert.ids).toEqual(['a', 'b', 'c'])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/configureStore.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/configureStore.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/configureStore.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,805 @@
+import type {
+  Action,
+  ConfigureStoreOptions,
+  Dispatch,
+  Middleware,
+  PayloadAction,
+  Reducer,
+  Store,
+  StoreEnhancer,
+  ThunkAction,
+  ThunkDispatch,
+  ThunkMiddleware,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  Tuple,
+  applyMiddleware,
+  combineReducers,
+  configureStore,
+  createSlice,
+} from '@reduxjs/toolkit'
+import { thunk } from 'redux-thunk'
+
+const _anyMiddleware: any = () => () => () => {}
+
+describe('type tests', () => {
+  test('configureStore() requires a valid reducer or reducer map.', () => {
+    configureStore({
+      reducer: (state, action) => 0,
+    })
+
+    configureStore({
+      reducer: {
+        counter1: () => 0,
+        counter2: () => 1,
+      },
+    })
+
+    // @ts-expect-error
+    configureStore({ reducer: 'not a reducer' })
+
+    // @ts-expect-error
+    configureStore({ reducer: { a: 'not a reducer' } })
+
+    // @ts-expect-error
+    configureStore({})
+  })
+
+  test('configureStore() infers the store state type.', () => {
+    const reducer: Reducer<number> = () => 0
+
+    const store = configureStore({ reducer })
+
+    expectTypeOf(store).toMatchTypeOf<Store<number, UnknownAction>>()
+
+    expectTypeOf(store).not.toMatchTypeOf<Store<string, UnknownAction>>()
+  })
+
+  test('configureStore() infers the store action type.', () => {
+    const reducer: Reducer<number, PayloadAction<number>> = () => 0
+
+    const store = configureStore({ reducer })
+
+    expectTypeOf(store).toMatchTypeOf<Store<number, PayloadAction<number>>>()
+
+    expectTypeOf(store).not.toMatchTypeOf<
+      Store<number, PayloadAction<string>>
+    >()
+  })
+
+  test('configureStore() accepts Tuple for middleware, but not plain array.', () => {
+    const middleware: Middleware = (store) => (next) => next
+
+    configureStore({
+      reducer: () => 0,
+      middleware: () => new Tuple(middleware),
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      middleware: () => [middleware],
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      middleware: () => new Tuple('not middleware'),
+    })
+  })
+
+  test('configureStore() accepts devTools flag.', () => {
+    configureStore({
+      reducer: () => 0,
+      devTools: true,
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      devTools: 'true',
+    })
+  })
+
+  test('configureStore() accepts devTools EnhancerOptions.', () => {
+    configureStore({
+      reducer: () => 0,
+      devTools: { name: 'myApp' },
+    })
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      devTools: { appName: 'myApp' },
+    })
+  })
+
+  test('configureStore() accepts preloadedState.', () => {
+    configureStore({
+      reducer: () => 0,
+      preloadedState: 0,
+    })
+
+    configureStore({
+      // @ts-expect-error
+      reducer: (_: number) => 0,
+      preloadedState: 'non-matching state type',
+    })
+  })
+
+  test('nullable state is preserved', () => {
+    const store = configureStore({
+      reducer: (): string | null => null,
+    })
+
+    expectTypeOf(store.getState()).toEqualTypeOf<string | null>()
+  })
+
+  test('configureStore() accepts store Tuple for enhancers, but not plain array', () => {
+    const enhancer = applyMiddleware(() => (next) => next)
+
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: () => new Tuple(enhancer),
+    })
+
+    const store2 = configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      enhancers: () => [enhancer],
+    })
+
+    expectTypeOf(store.dispatch).toMatchTypeOf<
+      Dispatch & ThunkDispatch<number, undefined, UnknownAction>
+    >()
+
+    configureStore({
+      reducer: () => 0,
+      // @ts-expect-error
+      enhancers: () => new Tuple('not a store enhancer'),
+    })
+
+    const somePropertyStoreEnhancer: StoreEnhancer<{
+      someProperty: string
+    }> = (next) => {
+      return (reducer, preloadedState) => {
+        return {
+          ...next(reducer, preloadedState),
+          someProperty: 'some value',
+        }
+      }
+    }
+
+    const anotherPropertyStoreEnhancer: StoreEnhancer<{
+      anotherProperty: number
+    }> = (next) => {
+      return (reducer, preloadedState) => {
+        return {
+          ...next(reducer, preloadedState),
+          anotherProperty: 123,
+        }
+      }
+    }
+
+    const store3 = configureStore({
+      reducer: () => 0,
+      enhancers: () =>
+        new Tuple(somePropertyStoreEnhancer, anotherPropertyStoreEnhancer),
+    })
+
+    expectTypeOf(store3.dispatch).toEqualTypeOf<Dispatch>()
+
+    expectTypeOf(store3.someProperty).toBeString()
+
+    expectTypeOf(store3.anotherProperty).toBeNumber()
+
+    const storeWithCallback = configureStore({
+      reducer: () => 0,
+      enhancers: (getDefaultEnhancers) =>
+        getDefaultEnhancers()
+          .prepend(anotherPropertyStoreEnhancer)
+          .concat(somePropertyStoreEnhancer),
+    })
+
+    expectTypeOf(store3.dispatch).toMatchTypeOf<
+      Dispatch & ThunkDispatch<number, undefined, UnknownAction>
+    >()
+
+    expectTypeOf(store3.someProperty).toBeString()
+
+    expectTypeOf(store3.anotherProperty).toBeNumber()
+
+    const someStateExtendingEnhancer: StoreEnhancer<
+      {},
+      { someProperty: string }
+    > =
+      (next) =>
+      (...args) => {
+        const store = next(...args)
+        const getState = () => ({
+          ...store.getState(),
+          someProperty: 'some value',
+        })
+        return {
+          ...store,
+          getState,
+        } as any
+      }
+
+    const anotherStateExtendingEnhancer: StoreEnhancer<
+      {},
+      { anotherProperty: number }
+    > =
+      (next) =>
+      (...args) => {
+        const store = next(...args)
+        const getState = () => ({
+          ...store.getState(),
+          anotherProperty: 123,
+        })
+        return {
+          ...store,
+          getState,
+        } as any
+      }
+
+    const store4 = configureStore({
+      reducer: () => ({ aProperty: 0 }),
+      enhancers: () =>
+        new Tuple(someStateExtendingEnhancer, anotherStateExtendingEnhancer),
+    })
+
+    const state = store4.getState()
+
+    expectTypeOf(state.aProperty).toBeNumber()
+
+    expectTypeOf(state.someProperty).toBeString()
+
+    expectTypeOf(state.anotherProperty).toBeNumber()
+
+    const storeWithCallback2 = configureStore({
+      reducer: () => ({ aProperty: 0 }),
+      enhancers: (gDE) =>
+        gDE().concat(someStateExtendingEnhancer, anotherStateExtendingEnhancer),
+    })
+
+    const stateWithCallback = storeWithCallback2.getState()
+
+    expectTypeOf(stateWithCallback.aProperty).toBeNumber()
+
+    expectTypeOf(stateWithCallback.someProperty).toBeString()
+
+    expectTypeOf(stateWithCallback.anotherProperty).toBeNumber()
+  })
+
+  test('Preloaded state typings', () => {
+    const counterReducer1: Reducer<number> = () => 0
+    const counterReducer2: Reducer<number> = () => 0
+
+    test('partial preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {
+          counter1: 0,
+        },
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('empty preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {},
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('excess properties in preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {
+          counter1: 0,
+          counter3: 5,
+        },
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('mismatching properties in preloaded state', () => {
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: {
+          counter3: 5,
+        },
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('string preloaded state when expecting object', () => {
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          counter1: counterReducer1,
+          counter2: counterReducer2,
+        },
+        preloadedState: 'test',
+      })
+
+      expectTypeOf(store.getState().counter1).toBeNumber()
+
+      expectTypeOf(store.getState().counter2).toBeNumber()
+    })
+
+    test('nested combineReducers allows partial', () => {
+      const store = configureStore({
+        reducer: {
+          group1: combineReducers({
+            counter1: counterReducer1,
+            counter2: counterReducer2,
+          }),
+          group2: combineReducers({
+            counter1: counterReducer1,
+            counter2: counterReducer2,
+          }),
+        },
+        preloadedState: {
+          group1: {
+            counter1: 5,
+          },
+        },
+      })
+
+      expectTypeOf(store.getState().group1.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group1.counter2).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter2).toBeNumber()
+    })
+
+    test('non-nested combineReducers does not allow partial', () => {
+      interface GroupState {
+        counter1: number
+        counter2: number
+      }
+
+      const initialState = { counter1: 0, counter2: 0 }
+
+      const group1Reducer: Reducer<GroupState> = (state = initialState) => state
+      const group2Reducer: Reducer<GroupState> = (state = initialState) => state
+
+      const store = configureStore({
+        reducer: {
+          // @ts-expect-error
+          group1: group1Reducer,
+          group2: group2Reducer,
+        },
+        preloadedState: {
+          group1: {
+            counter1: 5,
+          },
+        },
+      })
+
+      expectTypeOf(store.getState().group1.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group1.counter2).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter1).toBeNumber()
+
+      expectTypeOf(store.getState().group2.counter2).toBeNumber()
+    })
+  })
+
+  test('Dispatch typings', () => {
+    type StateA = number
+    const reducerA = () => 0
+    const thunkA = () => {
+      return (() => {}) as any as ThunkAction<Promise<'A'>, StateA, any, any>
+    }
+
+    type StateB = string
+    const thunkB = () => {
+      return (dispatch: Dispatch, getState: () => StateB) => {}
+    }
+
+    test('by default, dispatching Thunks is possible', () => {
+      const store = configureStore({
+        reducer: reducerA,
+      })
+
+      store.dispatch(thunkA())
+      // @ts-expect-error
+      store.dispatch(thunkB())
+
+      const res = store.dispatch((dispatch, getState) => {
+        return 42
+      })
+
+      const action = store.dispatch({ type: 'foo' })
+    })
+
+    test('return type of thunks and actions is inferred correctly', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: {
+          value: 0,
+        },
+        reducers: {
+          incrementByAmount: (state, action: PayloadAction<number>) => {
+            state.value += action.payload
+          },
+        },
+      })
+
+      const store = configureStore({
+        reducer: {
+          counter: slice.reducer,
+        },
+      })
+
+      const action = slice.actions.incrementByAmount(2)
+
+      const dispatchResult = store.dispatch(action)
+
+      expectTypeOf(dispatchResult).toMatchTypeOf<{
+        type: string
+        payload: number
+      }>()
+
+      const promiseResult = store.dispatch(async (dispatch) => {
+        return 42
+      })
+
+      expectTypeOf(promiseResult).toEqualTypeOf<Promise<number>>()
+
+      const store2 = configureStore({
+        reducer: {
+          counter: slice.reducer,
+        },
+        middleware: (gDM) =>
+          gDM({
+            thunk: {
+              extraArgument: 42,
+            },
+          }),
+      })
+
+      const dispatchResult2 = store2.dispatch(action)
+
+      expectTypeOf(dispatchResult2).toMatchTypeOf<{
+        type: string
+        payload: number
+      }>()
+    })
+
+    test('removing the Thunk Middleware', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () => new Tuple(),
+      })
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkA())
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('adding the thunk middleware by hand', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () => new Tuple(thunk as ThunkMiddleware<StateA>),
+      })
+
+      store.dispatch(thunkA())
+      // @ts-expect-error
+      store.dispatch(thunkB())
+    })
+
+    test('custom middleware', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () =>
+          new Tuple(0 as unknown as Middleware<(a: StateA) => boolean, StateA>),
+      })
+
+      expectTypeOf(store.dispatch(5)).toBeBoolean()
+
+      expectTypeOf(store.dispatch(5)).not.toBeString()
+    })
+
+    test('multiple custom middleware', () => {
+      const middleware = [] as any as Tuple<
+        [
+          Middleware<(a: 'a') => 'A', StateA>,
+          Middleware<(b: 'b') => 'B', StateA>,
+          ThunkMiddleware<StateA>,
+        ]
+      >
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: () => middleware,
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+    })
+
+    test('Accepts thunk with `unknown`, `undefined` or `null` ThunkAction extraArgument per default', () => {
+      const store = configureStore({ reducer: {} })
+      // undefined is the default value for the ThunkMiddleware extraArgument
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        undefined,
+        UnknownAction
+      >)
+      // `null` for the `extra` generic was previously documented in the RTK "Advanced Tutorial", but
+      // is a bad pattern and users should use `unknown` instead
+      // @ts-expect-error
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        null,
+        UnknownAction
+      >)
+      // unknown is the best way to type a ThunkAction if you do not care
+      // about the value of the extraArgument, as it will always work with every
+      // ThunkMiddleware, no matter the actual extraArgument type
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        unknown,
+        UnknownAction
+      >)
+      // @ts-expect-error
+      store.dispatch(function () {} as ThunkAction<
+        void,
+        {},
+        boolean,
+        UnknownAction
+      >)
+    })
+
+    test('custom middleware and getDefaultMiddleware', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (gDM) =>
+          gDM().prepend((() => {}) as any as Middleware<
+            (a: 'a') => 'A',
+            StateA
+          >),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('custom middleware and getDefaultMiddleware, using prepend', () => {
+      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
+        _anyMiddleware
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (gDM) => {
+          const concatenated = gDM().prepend(otherMiddleware)
+
+          expectTypeOf(concatenated).toMatchTypeOf<
+            ReadonlyArray<
+              typeof otherMiddleware | ThunkMiddleware | Middleware<{}>
+            >
+          >()
+
+          return concatenated
+        },
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('custom middleware and getDefaultMiddleware, using concat', () => {
+      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
+        _anyMiddleware
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (gDM) => {
+          const concatenated = gDM().concat(otherMiddleware)
+
+          expectTypeOf(concatenated).toMatchTypeOf<
+            ReadonlyArray<
+              typeof otherMiddleware | ThunkMiddleware | Middleware<{}>
+            >
+          >()
+
+          return concatenated
+        },
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('middlewareBuilder notation, getDefaultMiddleware (unconfigured)', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware().prepend((() => {}) as any as Middleware<
+            (a: 'a') => 'A',
+            StateA
+          >),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('middlewareBuilder notation, getDefaultMiddleware, concat & prepend', () => {
+      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
+        _anyMiddleware
+
+      const otherMiddleware2: Middleware<(a: 'b') => 'B', StateA> =
+        _anyMiddleware
+
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware()
+            .concat(otherMiddleware)
+            .prepend(otherMiddleware2),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
+
+      expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
+    })
+
+    test('middlewareBuilder notation, getDefaultMiddleware (thunk: false)', () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware({ thunk: false }).prepend(
+            (() => {}) as any as Middleware<(a: 'a') => 'A', StateA>,
+          ),
+      })
+
+      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
+
+      expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkA())
+    })
+
+    test("badly typed middleware won't make `dispatch` `any`", () => {
+      const store = configureStore({
+        reducer: reducerA,
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware().concat(_anyMiddleware as Middleware<any>),
+      })
+
+      expectTypeOf(store.dispatch).not.toBeAny()
+    })
+
+    test("decorated `configureStore` won't make `dispatch` `never`", () => {
+      const someSlice = createSlice({
+        name: 'something',
+        initialState: null as any,
+        reducers: {
+          set(state) {
+            return state
+          },
+        },
+      })
+
+      function configureMyStore<S>(
+        options: Omit<ConfigureStoreOptions<S>, 'reducer'>,
+      ) {
+        return configureStore({
+          ...options,
+          reducer: someSlice.reducer,
+        })
+      }
+
+      const store = configureMyStore({})
+
+      expectTypeOf(store.dispatch).toBeFunction()
+    })
+
+    interface CounterState {
+      value: number
+    }
+
+    const counterSlice = createSlice({
+      name: 'counter',
+      initialState: { value: 0 } as CounterState,
+      reducers: {
+        increment(state) {
+          state.value += 1
+        },
+        decrement(state) {
+          state.value -= 1
+        },
+        // Use the PayloadAction type to declare the contents of `action.payload`
+        incrementByAmount: (state, action: PayloadAction<number>) => {
+          state.value += action.payload
+        },
+      },
+    })
+
+    type Unsubscribe = () => void
+
+    // A fake middleware that tells TS that an unsubscribe callback is being returned for a given action
+    // This is the same signature that the "listener" middleware uses
+    const dummyMiddleware: Middleware<
+      {
+        (action: Action<'actionListenerMiddleware/add'>): Unsubscribe
+      },
+      CounterState
+    > = (storeApi) => (next) => (action) => {}
+
+    const store = configureStore({
+      reducer: counterSlice.reducer,
+      middleware: (gDM) => gDM().prepend(dummyMiddleware),
+    })
+
+    // Order matters here! We need the listener type to come first, otherwise
+    // the thunk middleware type kicks in and TS thinks a plain action is being returned
+    expectTypeOf(store.dispatch).toEqualTypeOf<
+      ((action: Action<'actionListenerMiddleware/add'>) => Unsubscribe) &
+        ThunkDispatch<CounterState, undefined, UnknownAction> &
+        Dispatch<UnknownAction>
+    >()
+
+    const unsubscribe = store.dispatch({
+      type: 'actionListenerMiddleware/add',
+    } as const)
+
+    expectTypeOf(unsubscribe).toEqualTypeOf<Unsubscribe>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/configureStore.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/configureStore.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/configureStore.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,371 @@
+import * as DevTools from '@internal/devtoolsExtension'
+import type { Middleware, StoreEnhancer } from '@reduxjs/toolkit'
+import { Tuple } from '@reduxjs/toolkit'
+import type * as Redux from 'redux'
+import { vi } from 'vitest'
+
+vi.doMock('redux', async (importOriginal) => {
+  const redux = await importOriginal<typeof import('redux')>()
+
+  vi.spyOn(redux, 'applyMiddleware')
+  vi.spyOn(redux, 'combineReducers')
+  vi.spyOn(redux, 'compose')
+  vi.spyOn(redux, 'createStore')
+
+  return redux
+})
+
+describe('configureStore', async () => {
+  const composeWithDevToolsSpy = vi.spyOn(DevTools, 'composeWithDevTools')
+
+  const redux = await import('redux')
+
+  const { configureStore } = await import('@reduxjs/toolkit')
+
+  const reducer: Redux.Reducer = (state = {}, _action) => state
+
+  beforeEach(() => {
+    vi.clearAllMocks()
+  })
+
+  describe('given a function reducer', () => {
+    it('calls createStore with the reducer', () => {
+      configureStore({ reducer })
+      expect(configureStore({ reducer })).toBeInstanceOf(Object)
+
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledTimes(2)
+      }
+    })
+  })
+
+  describe('given an object of reducers', () => {
+    it('calls createStore with the combined reducers', () => {
+      const reducer = {
+        reducer() {
+          return true
+        },
+      }
+      expect(configureStore({ reducer })).toBeInstanceOf(Object)
+      expect(redux.combineReducers).toHaveBeenCalledWith(reducer)
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        expect.any(Function),
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given no reducer', () => {
+    it('throws', () => {
+      expect(configureStore).toThrow(
+        '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
+      )
+    })
+  })
+
+  describe('given no middleware', () => {
+    it('calls createStore without any middleware', () => {
+      expect(
+        configureStore({ middleware: () => new Tuple(), reducer }),
+      ).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalledWith()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given an array of middleware', () => {
+    it('throws an error requiring a callback', () => {
+      // @ts-expect-error
+      expect(() => configureStore({ middleware: [], reducer })).toThrow(
+        '`middleware` field must be a callback',
+      )
+    })
+  })
+
+  describe('given undefined middleware', () => {
+    it('calls createStore with default middleware', () => {
+      expect(configureStore({ middleware: undefined, reducer })).toBeInstanceOf(
+        Object,
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalledWith(
+        expect.any(Function), // immutableCheck
+        expect.any(Function), // thunk
+        expect.any(Function), // serializableCheck
+        expect.any(Function), // actionCreatorCheck
+      )
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given any middleware', () => {
+    const exampleMiddleware: Middleware<any, any> = () => (next) => (action) =>
+      next(action)
+    it('throws an error by default if there are duplicate middleware', () => {
+      const makeStore = () => {
+        return configureStore({
+          reducer,
+          middleware: (gDM) =>
+            gDM().concat(exampleMiddleware, exampleMiddleware),
+        })
+      }
+
+      expect(makeStore).toThrowError(
+        'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
+      )
+    })
+
+    it('does not throw a duplicate middleware error if duplicateMiddlewareCheck is disabled', () => {
+      const makeStore = () => {
+        return configureStore({
+          reducer,
+          middleware: (gDM) =>
+            gDM().concat(exampleMiddleware, exampleMiddleware),
+          duplicateMiddlewareCheck: false,
+        })
+      }
+
+      expect(makeStore).not.toThrowError()
+    })
+  })
+
+  describe('given a middleware creation function that returns undefined', () => {
+    it('throws an error', () => {
+      const invalidBuilder = vi.fn((getDefaultMiddleware) => undefined as any)
+      expect(() =>
+        configureStore({ middleware: invalidBuilder, reducer }),
+      ).toThrow(
+        'when using a middleware builder function, an array of middleware must be returned',
+      )
+    })
+  })
+
+  describe('given a middleware creation function that returns an array with non-functions', () => {
+    it('throws an error', () => {
+      const invalidBuilder = vi.fn((getDefaultMiddleware) => [true] as any)
+      expect(() =>
+        configureStore({ middleware: invalidBuilder, reducer }),
+      ).toThrow('each middleware provided to configureStore must be a function')
+    })
+  })
+
+  describe('given custom middleware', () => {
+    it('calls createStore with custom middleware and without default middleware', () => {
+      const thank: Redux.Middleware = (_store) => (next) => (action) =>
+        next(action)
+      expect(
+        configureStore({ middleware: () => new Tuple(thank), reducer }),
+      ).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalledWith(thank)
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('middleware builder notation', () => {
+    it('calls builder, passes getDefaultMiddleware and uses returned middlewares', () => {
+      const thank = vi.fn(
+        ((_store) => (next) => (action) => 'foobar') as Redux.Middleware,
+      )
+
+      const builder = vi.fn((getDefaultMiddleware) => {
+        expect(getDefaultMiddleware).toEqual(expect.any(Function))
+        expect(getDefaultMiddleware()).toEqual(expect.any(Array))
+
+        return new Tuple(thank)
+      })
+
+      const store = configureStore({ middleware: builder, reducer })
+
+      expect(builder).toHaveBeenCalled()
+
+      expect(store.dispatch({ type: 'test' })).toBe('foobar')
+    })
+  })
+
+  describe('with devTools disabled', () => {
+    it('calls createStore without devTools enhancer', () => {
+      expect(configureStore({ devTools: false, reducer })).toBeInstanceOf(
+        Object,
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      expect(redux.compose).toHaveBeenCalled()
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('with devTools options', () => {
+    it('calls createStore with devTools enhancer and option', () => {
+      const options = {
+        name: 'myApp',
+        trace: true,
+      }
+      expect(configureStore({ devTools: options, reducer })).toBeInstanceOf(
+        Object,
+      )
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+
+        expect(composeWithDevToolsSpy).toHaveBeenLastCalledWith(options)
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given preloadedState', () => {
+    it('calls createStore with preloadedState', () => {
+      expect(configureStore({ reducer })).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+    })
+  })
+
+  describe('given enhancers', () => {
+    let dummyEnhancerCalled = false
+
+    const dummyEnhancer: StoreEnhancer =
+      (createStore) => (reducer, preloadedState) => {
+        dummyEnhancerCalled = true
+
+        return createStore(reducer, preloadedState)
+      }
+
+    beforeEach(() => {
+      dummyEnhancerCalled = false
+    })
+
+    it('calls createStore with enhancers', () => {
+      expect(
+        configureStore({
+          enhancers: (gDE) => gDE().concat(dummyEnhancer),
+          reducer,
+        }),
+      ).toBeInstanceOf(Object)
+      expect(redux.applyMiddleware).toHaveBeenCalled()
+      if (process.env.TEST_DIST) {
+        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()
+      } else {
+        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()
+      }
+      expect(redux.createStore).toHaveBeenCalledWith(
+        reducer,
+        undefined,
+        expect.any(Function),
+      )
+
+      expect(dummyEnhancerCalled).toBe(true)
+    })
+
+    describe('invalid arguments', () => {
+      test('enhancers is not a callback', () => {
+        expect(() => configureStore({ reducer, enhancers: [] as any })).toThrow(
+          '`enhancers` field must be a callback',
+        )
+      })
+
+      test('callback fails to return array', () => {
+        expect(() =>
+          configureStore({ reducer, enhancers: (() => {}) as any }),
+        ).toThrow('`enhancers` callback must return an array')
+      })
+
+      test('array contains non-function', () => {
+        expect(() =>
+          configureStore({ reducer, enhancers: (() => ['']) as any }),
+        ).toThrow('each enhancer provided to configureStore must be a function')
+      })
+    })
+
+    const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+    beforeEach(() => {
+      consoleSpy.mockClear()
+    })
+    afterAll(() => {
+      consoleSpy.mockRestore()
+    })
+
+    it('warns if middleware enhancer is excluded from final array when middlewares are provided', () => {
+      const store = configureStore({
+        reducer,
+        enhancers: () => new Tuple(dummyEnhancer),
+      })
+
+      expect(dummyEnhancerCalled).toBe(true)
+
+      expect(consoleSpy).toHaveBeenCalledWith(
+        'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
+      )
+    })
+    it("doesn't warn when middleware enhancer is excluded if no middlewares provided", () => {
+      const store = configureStore({
+        reducer,
+        middleware: () => new Tuple(),
+        enhancers: () => new Tuple(dummyEnhancer),
+      })
+
+      expect(dummyEnhancerCalled).toBe(true)
+
+      expect(consoleSpy).not.toHaveBeenCalled()
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAction.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAction.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAction.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,326 @@
+import type {
+  Action,
+  ActionCreator,
+  ActionCreatorWithNonInferrablePayload,
+  ActionCreatorWithOptionalPayload,
+  ActionCreatorWithPayload,
+  ActionCreatorWithPreparedPayload,
+  ActionCreatorWithoutPayload,
+  PayloadAction,
+  PayloadActionCreator,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { createAction } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  describe('PayloadAction', () => {
+    test('PayloadAction has type parameter for the payload.', () => {
+      const action: PayloadAction<number> = { type: '', payload: 5 }
+
+      expectTypeOf(action.payload).toBeNumber()
+
+      expectTypeOf(action.payload).not.toBeString()
+    })
+
+    test('PayloadAction type parameter is required.', () => {
+      expectTypeOf({ type: '', payload: 5 }).not.toMatchTypeOf<PayloadAction>()
+    })
+
+    test('PayloadAction has a string type tag.', () => {
+      expectTypeOf({ type: '', payload: 5 }).toEqualTypeOf<
+        PayloadAction<number>
+      >()
+
+      expectTypeOf({ type: 1, payload: 5 }).not.toMatchTypeOf<PayloadAction>()
+    })
+
+    test('PayloadAction is compatible with Action<string>', () => {
+      const action: PayloadAction<number> = { type: '', payload: 5 }
+
+      expectTypeOf(action).toMatchTypeOf<Action<string>>()
+    })
+  })
+
+  describe('PayloadActionCreator', () => {
+    test('PayloadActionCreator returns correctly typed PayloadAction depending on whether a payload is passed.', () => {
+      const actionCreator = Object.assign(
+        (payload?: number) => ({
+          type: 'action',
+          payload,
+        }),
+        { type: 'action' },
+      ) as PayloadActionCreator<number | undefined>
+
+      expectTypeOf(actionCreator(1)).toEqualTypeOf<
+        PayloadAction<number | undefined>
+      >()
+
+      expectTypeOf(actionCreator()).toEqualTypeOf<
+        PayloadAction<number | undefined>
+      >()
+
+      expectTypeOf(actionCreator(undefined)).toEqualTypeOf<
+        PayloadAction<number | undefined>
+      >()
+
+      expectTypeOf(actionCreator()).not.toMatchTypeOf<PayloadAction<number>>()
+
+      expectTypeOf(actionCreator(1)).not.toMatchTypeOf<
+        PayloadAction<undefined>
+      >()
+    })
+
+    test('PayloadActionCreator is compatible with ActionCreator.', () => {
+      const payloadActionCreator = Object.assign(
+        (payload?: number) => ({
+          type: 'action',
+          payload,
+        }),
+        { type: 'action' },
+      ) as PayloadActionCreator
+
+      expectTypeOf(payloadActionCreator).toMatchTypeOf<
+        ActionCreator<UnknownAction>
+      >()
+
+      const payloadActionCreator2 = Object.assign(
+        (payload?: number) => ({
+          type: 'action',
+          payload: payload || 1,
+        }),
+        { type: 'action' },
+      ) as PayloadActionCreator<number>
+
+      expectTypeOf(payloadActionCreator2).toMatchTypeOf<
+        ActionCreator<PayloadAction<number>>
+      >()
+    })
+  })
+
+  test('createAction() has type parameter for the action payload.', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    expectTypeOf(increment).parameter(0).toBeNumber()
+
+    expectTypeOf(increment).parameter(0).not.toBeString()
+  })
+
+  test('createAction() type parameter is required, not inferred (defaults to `void`).', () => {
+    const increment = createAction('increment')
+
+    expectTypeOf(increment).parameter(0).not.toBeNumber()
+
+    expectTypeOf(increment().payload).not.toBeNumber()
+  })
+
+  test('createAction().type is a string literal.', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    expectTypeOf(increment(1).type).toBeString()
+
+    expectTypeOf(increment(1).type).toEqualTypeOf<'increment'>()
+
+    expectTypeOf(increment(1).type).not.toMatchTypeOf<'other'>()
+
+    expectTypeOf(increment(1).type).not.toBeNumber()
+  })
+
+  test('type still present when using prepareAction', () => {
+    const strLenAction = createAction('strLen', (payload: string) => ({
+      payload: payload.length,
+    }))
+
+    expectTypeOf(strLenAction('test').type).toBeString()
+  })
+
+  test('changing payload type with prepareAction', () => {
+    const strLenAction = createAction('strLen', (payload: string) => ({
+      payload: payload.length,
+    }))
+
+    expectTypeOf(strLenAction('test').payload).toBeNumber()
+
+    expectTypeOf(strLenAction('test').payload).not.toBeString()
+
+    expectTypeOf(strLenAction('test')).not.toHaveProperty('error')
+  })
+
+  test('adding metadata with prepareAction', () => {
+    const strLenMetaAction = createAction('strLenMeta', (payload: string) => ({
+      payload,
+      meta: payload.length,
+    }))
+
+    expectTypeOf(strLenMetaAction('test').meta).toBeNumber()
+
+    expectTypeOf(strLenMetaAction('test').meta).not.toBeString()
+
+    expectTypeOf(strLenMetaAction('test')).not.toHaveProperty('error')
+  })
+
+  test('adding boolean error with prepareAction', () => {
+    const boolErrorAction = createAction('boolError', (payload: string) => ({
+      payload,
+      error: true,
+    }))
+
+    expectTypeOf(boolErrorAction('test').error).toBeBoolean()
+
+    expectTypeOf(boolErrorAction('test').error).not.toBeString()
+  })
+
+  test('adding string error with prepareAction', () => {
+    const strErrorAction = createAction('strError', (payload: string) => ({
+      payload,
+      error: 'this is an error',
+    }))
+
+    expectTypeOf(strErrorAction('test').error).toBeString()
+
+    expectTypeOf(strErrorAction('test').error).not.toBeBoolean()
+  })
+
+  test('regression test for https://github.com/reduxjs/redux-toolkit/issues/214', () => {
+    const action = createAction<{ input?: string }>('ACTION')
+
+    expectTypeOf(action({ input: '' }).payload.input).toEqualTypeOf<
+      string | undefined
+    >()
+
+    expectTypeOf(action({ input: '' }).payload.input).not.toBeNumber()
+
+    expectTypeOf(action).parameter(0).not.toMatchTypeOf({ input: 3 })
+  })
+
+  test('regression test for https://github.com/reduxjs/redux-toolkit/issues/224', () => {
+    const oops = createAction('oops', (x: any) => ({
+      payload: x,
+      error: x,
+      meta: x,
+    }))
+
+    expectTypeOf(oops('').payload).toBeAny()
+
+    expectTypeOf(oops('').error).toBeAny()
+
+    expectTypeOf(oops('').meta).toBeAny()
+  })
+
+  describe('createAction.match()', () => {
+    test('simple use case', () => {
+      const actionCreator = createAction<string, 'test'>('test')
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).toBeString()
+      } else {
+        expectTypeOf(x.type).not.toMatchTypeOf<'test'>()
+
+        expectTypeOf(x).not.toHaveProperty('payload')
+      }
+    })
+
+    test('special case: optional argument', () => {
+      const actionCreator = createAction<string | undefined, 'test'>('test')
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).toEqualTypeOf<string | undefined>()
+      }
+    })
+
+    test('special case: without argument', () => {
+      const actionCreator = createAction('test')
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).not.toMatchTypeOf<{}>()
+      }
+    })
+
+    test('special case: with prepareAction', () => {
+      const actionCreator = createAction('test', () => ({
+        payload: '',
+        meta: '',
+        error: false,
+      }))
+
+      const x: Action<string> = {} as any
+
+      if (actionCreator.match(x)) {
+        expectTypeOf(x.type).toEqualTypeOf<'test'>()
+
+        expectTypeOf(x.payload).toBeString()
+
+        expectTypeOf(x.meta).toBeString()
+
+        expectTypeOf(x.error).toBeBoolean()
+
+        expectTypeOf(x.payload).not.toBeNumber()
+
+        expectTypeOf(x.meta).not.toBeNumber()
+
+        expectTypeOf(x.error).not.toBeNumber()
+      }
+    })
+    test('potential use: as array filter', () => {
+      const actionCreator = createAction<string, 'test'>('test')
+
+      const x: Action<string>[] = []
+
+      expectTypeOf(x.filter(actionCreator.match)).toEqualTypeOf<
+        PayloadAction<string, 'test'>[]
+      >()
+    })
+  })
+
+  test('ActionCreatorWithOptionalPayload', () => {
+    expectTypeOf(createAction<string | undefined>('')).toEqualTypeOf<
+      ActionCreatorWithOptionalPayload<string | undefined>
+    >()
+
+    expectTypeOf(
+      createAction<void>(''),
+    ).toEqualTypeOf<ActionCreatorWithoutPayload>()
+
+    assertType<ActionCreatorWithNonInferrablePayload>(createAction(''))
+
+    expectTypeOf(createAction<string>('')).toEqualTypeOf<
+      ActionCreatorWithPayload<string>
+    >()
+
+    expectTypeOf(
+      createAction('', (_: 0) => ({
+        payload: 1 as 1,
+        error: 2 as 2,
+        meta: 3 as 3,
+      })),
+    ).toEqualTypeOf<ActionCreatorWithPreparedPayload<[0], 1, '', 2, 3>>()
+
+    const anyCreator = createAction<any>('')
+
+    expectTypeOf(anyCreator).toEqualTypeOf<ActionCreatorWithPayload<any>>()
+
+    expectTypeOf(anyCreator({}).payload).toBeAny()
+  })
+
+  test("Verify action creators should not be passed directly as arguments to React event handlers if there shouldn't be a payload", () => {
+    const emptyAction = createAction<void>('empty/action')
+
+    function TestComponent() {
+      // This typically leads to an error like:
+      //  // A non-serializable value was detected in an action, in the path: `payload`.
+      // @ts-expect-error Should error because `void` and `MouseEvent` aren't compatible
+      return <button onClick={emptyAction}>+</button>
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAction.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAction.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAction.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,148 @@
+import { createAction, isActionCreator } from '@reduxjs/toolkit'
+
+describe('createAction', () => {
+  it('should create an action', () => {
+    const actionCreator = createAction<string>('A_TYPE')
+    expect(actionCreator('something')).toEqual({
+      type: 'A_TYPE',
+      payload: 'something',
+    })
+  })
+
+  describe('when stringifying action', () => {
+    it('should return the action type', () => {
+      const actionCreator = createAction('A_TYPE')
+      expect(`${actionCreator}`).toEqual('A_TYPE')
+    })
+  })
+
+  describe('when passing a prepareAction method only returning a payload', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should not have a meta attribute on the resulting Action', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+      }))
+      expect('meta' in actionCreator(5)).toBeFalsy()
+    })
+  })
+
+  describe('when passing a prepareAction method returning a payload and meta', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should use the meta returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+      }))
+      expect(actionCreator(10).meta).toBe(5)
+    })
+  })
+
+  describe('when passing a prepareAction method returning a payload and error', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        error: true,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should use the error returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        error: true,
+      }))
+      expect(actionCreator(10).error).toBe(true)
+    })
+  })
+
+  describe('when passing a prepareAction method returning a payload, meta and error', () => {
+    it('should use the payload returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+        error: true,
+      }))
+      expect(actionCreator(5).payload).toBe(10)
+    })
+    it('should use the error returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+        error: true,
+      }))
+      expect(actionCreator(10).error).toBe(true)
+    })
+    it('should use the meta returned from the prepareAction method', () => {
+      const actionCreator = createAction('A_TYPE', (a: number) => ({
+        payload: a * 2,
+        meta: a / 2,
+        error: true,
+      }))
+      expect(actionCreator(10).meta).toBe(5)
+    })
+  })
+
+  describe('when passing a prepareAction that accepts multiple arguments', () => {
+    it('should pass all arguments of the resulting actionCreator to prepareAction', () => {
+      const actionCreator = createAction(
+        'A_TYPE',
+        (a: string, b: string, c: string) => ({
+          payload: a + b + c,
+        }),
+      )
+      expect(actionCreator('1', '2', '3').payload).toBe('123')
+    })
+  })
+
+  describe('actionCreator.match', () => {
+    test('should return true for actions generated by own actionCreator', () => {
+      const actionCreator = createAction('test')
+      expect(actionCreator.match(actionCreator())).toBe(true)
+    })
+
+    test('should return true for matching actions', () => {
+      const actionCreator = createAction('test')
+      expect(actionCreator.match({ type: 'test' })).toBe(true)
+    })
+
+    test('should return false for other actions', () => {
+      const actionCreator = createAction('test')
+      expect(actionCreator.match({ type: 'test-abc' })).toBe(false)
+    })
+  })
+})
+
+const actionCreator = createAction('anAction')
+
+class Action {
+  type = 'totally an action'
+}
+
+describe('isActionCreator', () => {
+  it('should only return true for action creators', () => {
+    expect(isActionCreator(actionCreator)).toBe(true)
+    const notActionCreators = [
+      { type: 'an action' },
+      { type: 'more props', extra: true },
+      actionCreator(),
+      Promise.resolve({ type: 'an action' }),
+      new Action(),
+      false,
+      'a string',
+      false,
+    ]
+    for (const notActionCreator of notActionCreators) {
+      expect(isActionCreator(notActionCreator)).toBe(false)
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,899 @@
+import type {
+  AsyncThunk,
+  SerializedError,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAsyncThunk,
+  createReducer,
+  createSlice,
+  unwrapResult,
+} from '@reduxjs/toolkit'
+
+import type { TSVersion } from '@phryneas/ts-version'
+import type { AxiosError } from 'axios'
+import apiRequest from 'axios'
+import type { AsyncThunkDispatchConfig } from '@internal/createAsyncThunk'
+
+const defaultDispatch = (() => {}) as ThunkDispatch<{}, any, UnknownAction>
+const unknownAction = { type: 'foo' } as UnknownAction
+
+describe('type tests', () => {
+  test('basic usage', async () => {
+    const asyncThunk = createAsyncThunk('test', (id: number) =>
+      Promise.resolve(id * 2),
+    )
+
+    const reducer = createReducer({}, (builder) =>
+      builder
+        .addCase(asyncThunk.pending, (_, action) => {
+          expectTypeOf(action).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['pending']>
+          >()
+        })
+
+        .addCase(asyncThunk.fulfilled, (_, action) => {
+          expectTypeOf(action).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['fulfilled']>
+          >()
+
+          expectTypeOf(action.payload).toBeNumber()
+        })
+
+        .addCase(asyncThunk.rejected, (_, action) => {
+          expectTypeOf(action).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['rejected']>
+          >()
+
+          expectTypeOf(action.error).toMatchTypeOf<Partial<Error> | undefined>()
+        }),
+    )
+
+    const promise = defaultDispatch(asyncThunk(3))
+
+    expectTypeOf(promise.requestId).toBeString()
+
+    expectTypeOf(promise.arg).toBeNumber()
+
+    expectTypeOf(promise.abort).toEqualTypeOf<(reason?: string) => void>()
+
+    const result = await promise
+
+    if (asyncThunk.fulfilled.match(result)) {
+      expectTypeOf(result).toEqualTypeOf<
+        ReturnType<(typeof asyncThunk)['fulfilled']>
+      >()
+    } else {
+      expectTypeOf(result).toEqualTypeOf<
+        ReturnType<(typeof asyncThunk)['rejected']>
+      >()
+    }
+
+    promise
+      .then(unwrapResult)
+      .then((result) => {
+        expectTypeOf(result).toBeNumber()
+
+        expectTypeOf(result).not.toMatchTypeOf<Error>()
+      })
+      .catch((error) => {
+        // catch is always any-typed, nothing we can do here
+        expectTypeOf(error).toBeAny()
+      })
+  })
+
+  test('More complex usage of thunk args', () => {
+    interface BookModel {
+      id: string
+      title: string
+    }
+
+    type BooksState = BookModel[]
+
+    const fakeBooks: BookModel[] = [
+      { id: 'b', title: 'Second' },
+      { id: 'a', title: 'First' },
+    ]
+
+    const correctDispatch = (() => {}) as ThunkDispatch<
+      BookModel[],
+      { userAPI: Function },
+      UnknownAction
+    >
+
+    // Verify that the the first type args to createAsyncThunk line up right
+    const fetchBooksTAC = createAsyncThunk<
+      BookModel[],
+      number,
+      {
+        state: BooksState
+        extra: { userAPI: Function }
+      }
+    >(
+      'books/fetch',
+      async (arg, { getState, dispatch, extra, requestId, signal }) => {
+        const state = getState()
+
+        expectTypeOf(arg).toBeNumber()
+
+        expectTypeOf(state).toEqualTypeOf<BookModel[]>()
+
+        expectTypeOf(extra).toEqualTypeOf<{ userAPI: Function }>()
+
+        return fakeBooks
+      },
+    )
+
+    correctDispatch(fetchBooksTAC(1))
+    // @ts-expect-error
+    defaultDispatch(fetchBooksTAC(1))
+  })
+
+  test('returning a rejected action from the promise creator is possible', async () => {
+    type ReturnValue = { data: 'success' }
+    type RejectValue = { data: 'error' }
+
+    const fetchBooksTAC = createAsyncThunk<
+      ReturnValue,
+      number,
+      {
+        rejectValue: RejectValue
+      }
+    >('books/fetch', async (arg, { rejectWithValue }) => {
+      return rejectWithValue({ data: 'error' })
+    })
+
+    const returned = await defaultDispatch(fetchBooksTAC(1))
+    if (fetchBooksTAC.rejected.match(returned)) {
+      expectTypeOf(returned.payload).toEqualTypeOf<undefined | RejectValue>()
+
+      expectTypeOf(returned.payload).toBeNullable()
+    } else {
+      expectTypeOf(returned.payload).toEqualTypeOf<ReturnValue>()
+    }
+
+    expectTypeOf(unwrapResult(returned)).toEqualTypeOf<ReturnValue>()
+
+    expectTypeOf(unwrapResult(returned)).not.toMatchTypeOf<RejectValue>()
+  })
+
+  test('regression #1156: union return values fall back to allowing only single member', () => {
+    const fn = createAsyncThunk('session/isAdmin', async () => {
+      const response: boolean = false
+      return response
+    })
+  })
+
+  test('Should handle reject with value within a try catch block. Note: this is a sample code taken from #1605', () => {
+    type ResultType = {
+      text: string
+    }
+    const demoPromise = async (): Promise<ResultType> =>
+      new Promise((resolve, _) => resolve({ text: '' }))
+    const thunk = createAsyncThunk('thunk', async (args, thunkAPI) => {
+      try {
+        const result = await demoPromise()
+        return result
+      } catch (error) {
+        return thunkAPI.rejectWithValue(error)
+      }
+    })
+    createReducer({}, (builder) =>
+      builder.addCase(thunk.fulfilled, (s, action) => {
+        expectTypeOf(action.payload).toEqualTypeOf<ResultType>()
+      }),
+    )
+  })
+
+  test('reject with value', () => {
+    interface Item {
+      name: string
+    }
+
+    interface ErrorFromServer {
+      error: string
+    }
+
+    interface CallsResponse {
+      data: Item[]
+    }
+
+    const fetchLiveCallsError = createAsyncThunk<
+      Item[],
+      string,
+      {
+        rejectValue: ErrorFromServer
+      }
+    >('calls/fetchLiveCalls', async (organizationId, { rejectWithValue }) => {
+      try {
+        const result = await apiRequest.get<CallsResponse>(
+          `organizations/${organizationId}/calls/live/iwill404`,
+        )
+        return result.data.data
+      } catch (err) {
+        const error: AxiosError<ErrorFromServer> = err as any // cast for access to AxiosError properties
+        if (!error.response) {
+          // let it be handled as any other unknown error
+          throw err
+        }
+        return rejectWithValue(error.response && error.response.data)
+      }
+    })
+
+    defaultDispatch(fetchLiveCallsError('asd')).then((result) => {
+      if (fetchLiveCallsError.fulfilled.match(result)) {
+        //success
+        expectTypeOf(result).toEqualTypeOf<
+          ReturnType<(typeof fetchLiveCallsError)['fulfilled']>
+        >()
+
+        expectTypeOf(result.payload).toEqualTypeOf<Item[]>()
+      } else {
+        expectTypeOf(result).toEqualTypeOf<
+          ReturnType<(typeof fetchLiveCallsError)['rejected']>
+        >()
+
+        if (result.payload) {
+          // rejected with value
+          expectTypeOf(result.payload).toEqualTypeOf<ErrorFromServer>()
+        } else {
+          // rejected by throw
+          expectTypeOf(result.payload).toBeUndefined()
+
+          expectTypeOf(result.error).toEqualTypeOf<SerializedError>()
+
+          expectTypeOf(result.error).not.toBeAny()
+        }
+      }
+      defaultDispatch(fetchLiveCallsError('asd'))
+        .then((result) => {
+          expectTypeOf(result.payload).toEqualTypeOf<
+            Item[] | ErrorFromServer | undefined
+          >()
+
+          return result
+        })
+        .then(unwrapResult)
+        .then((unwrapped) => {
+          expectTypeOf(unwrapped).toEqualTypeOf<Item[]>()
+
+          expectTypeOf(unwrapResult).parameter(0).not.toMatchTypeOf(unwrapped)
+        })
+    })
+  })
+
+  describe('payloadCreator first argument type has impact on asyncThunk argument', () => {
+    test('asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', () => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+
+      expectTypeOf(asyncThunk).returns.toBeFunction()
+    })
+
+    test('one argument, specified as undefined: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: undefined) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+    })
+
+    test('one argument, specified as void: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: void) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+    })
+
+    test('one argument, specified as optional number: asyncThunk has optional number argument', () => {
+      // this test will fail with strictNullChecks: false, that is to be expected
+      // in that case, we have to forbid this behavior or it will make arguments optional everywhere
+      const asyncThunk = createAsyncThunk('test', (arg?: number) => 0)
+
+      // Per https://github.com/reduxjs/redux-toolkit/issues/3758#issuecomment-1742152774 , this is a bug in
+      // TS 5.1 and 5.2, that is fixed in 5.3. Conditionally run the TS assertion here.
+      type IsTS51Or52 = TSVersion.Major extends 5
+        ? TSVersion.Minor extends 1 | 2
+          ? true
+          : false
+        : false
+
+      type expectedType = IsTS51Or52 extends true
+        ? (arg: number) => any
+        : (arg?: number) => any
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<expectedType>()
+
+      // We _should_ be able to call this with no arguments, but we run into that error in 5.1 and 5.2.
+      // Disabling this for now.
+      // asyncThunk()
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
+    })
+
+    test('one argument, specified as number|undefined: asyncThunk has optional number argument', () => {
+      // this test will fail with strictNullChecks: false, that is to be expected
+      // in that case, we have to forbid this behavior or it will make arguments optional everywhere
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: number | undefined) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
+    })
+
+    test('one argument, specified as number|void: asyncThunk has optional number argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: number | void) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[string]>()
+    })
+
+    test('one argument, specified as any: asyncThunk has required any argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: any) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeAny()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('one argument, specified as unknown: asyncThunk has required unknown argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: unknown) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeUnknown()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('one argument, specified as number: asyncThunk has required number argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: number) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('two arguments, first specified as undefined: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: undefined, thunkApi) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      // cannot be called with an argument
+      expectTypeOf(asyncThunk).parameter(0).not.toBeAny()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+    })
+
+    test('two arguments, first specified as void: asyncThunk has no argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: void, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<() => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).parameter(0).toBeVoid()
+
+      // cannot be called with an argument
+      expectTypeOf(asyncThunk).parameter(0).not.toBeAny()
+
+      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<
+        [undefined?, AsyncThunkDispatchConfig?]
+      >()
+    })
+
+    test('two arguments, first specified as number|undefined: asyncThunk has optional number argument', () => {
+      // this test will fail with strictNullChecks: false, that is to be expected
+      // in that case, we have to forbid this behavior or it will make arguments optional everywhere
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: number | undefined, thunkApi) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameter(0).not.toBeString()
+    })
+
+    test('two arguments, first specified as number|void: asyncThunk has optional number argument', () => {
+      const asyncThunk = createAsyncThunk(
+        'test',
+        (arg: number | void, thunkApi) => 0,
+      )
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg?: number) => any>()
+
+      expectTypeOf(asyncThunk).toBeCallableWith()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(undefined)
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameter(0).not.toBeString()
+    })
+
+    test('two arguments, first specified as any: asyncThunk has required any argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: any, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeAny()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('two arguments, first specified as unknown: asyncThunk has required unknown argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: unknown, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).parameter(0).toBeUnknown()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+
+    test('two arguments, first specified as number: asyncThunk has required number argument', () => {
+      const asyncThunk = createAsyncThunk('test', (arg: number, thunkApi) => 0)
+
+      expectTypeOf(asyncThunk).toMatchTypeOf<(arg: number) => any>()
+
+      expectTypeOf(asyncThunk).parameter(0).toBeNumber()
+
+      expectTypeOf(asyncThunk).toBeCallableWith(5)
+
+      expectTypeOf(asyncThunk).parameters.not.toMatchTypeOf<[]>()
+    })
+  })
+
+  test('createAsyncThunk without generics', () => {
+    const thunk = createAsyncThunk('test', () => {
+      return 'ret' as const
+    })
+
+    expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()
+  })
+
+  test('createAsyncThunk without generics, accessing `api` does not break return type', () => {
+    const thunk = createAsyncThunk('test', (_: void, api) => {
+      return 'ret' as const
+    })
+
+    expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()
+  })
+
+  test('createAsyncThunk rejectWithValue without generics: Expect correct return type', () => {
+    const asyncThunk = createAsyncThunk(
+      'test',
+      (_: void, { rejectWithValue }) => {
+        try {
+          return Promise.resolve(true)
+        } catch (e) {
+          return rejectWithValue(e)
+        }
+      },
+    )
+
+    defaultDispatch(asyncThunk())
+      .then((result) => {
+        if (asyncThunk.fulfilled.match(result)) {
+          expectTypeOf(result).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['fulfilled']>
+          >()
+
+          expectTypeOf(result.payload).toBeBoolean()
+
+          expectTypeOf(result).not.toHaveProperty('error')
+        } else {
+          expectTypeOf(result).toEqualTypeOf<
+            ReturnType<(typeof asyncThunk)['rejected']>
+          >()
+
+          expectTypeOf(result.error).toEqualTypeOf<SerializedError>()
+
+          expectTypeOf(result.payload).toBeUnknown()
+        }
+
+        return result
+      })
+      .then(unwrapResult)
+      .then((unwrapped) => {
+        expectTypeOf(unwrapped).toBeBoolean()
+      })
+  })
+
+  test('createAsyncThunk with generics', () => {
+    type Funky = { somethingElse: 'Funky!' }
+    function funkySerializeError(err: any): Funky {
+      return { somethingElse: 'Funky!' }
+    }
+
+    // has to stay on one line or type tests fail in older TS versions
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFail = createAsyncThunk('without generics', () => {}, { serializeError: funkySerializeError })
+
+    const shouldWork = createAsyncThunk<
+      any,
+      void,
+      { serializedErrorType: Funky }
+    >('with generics', () => {}, {
+      serializeError: funkySerializeError,
+    })
+
+    if (shouldWork.rejected.match(unknownAction)) {
+      expectTypeOf(unknownAction.error).toEqualTypeOf<Funky>()
+    }
+  })
+
+  test('`idGenerator` option takes no arguments, and returns a string', () => {
+    const returnsNumWithArgs = (foo: any) => 100
+    // has to stay on one line or type tests fail in older TS versions
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFailNumWithArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithArgs })
+
+    const returnsNumWithoutArgs = () => 100
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFailNumWithoutArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithoutArgs })
+
+    const returnsStrWithNumberArg = (foo: number) => 'foo'
+    // prettier-ignore
+    // @ts-expect-error
+    const shouldFailWrongArgs = createAsyncThunk('foo', (arg: string) => {}, { idGenerator: returnsStrWithNumberArg })
+
+    const returnsStrWithStringArg = (foo: string) => 'foo'
+    const shoulducceedCorrectArgs = createAsyncThunk(
+      'foo',
+      (arg: string) => {},
+      {
+        idGenerator: returnsStrWithStringArg,
+      },
+    )
+
+    const returnsStrWithoutArgs = () => 'foo'
+    const shouldSucceed = createAsyncThunk('foo', () => {}, {
+      idGenerator: returnsStrWithoutArgs,
+    })
+  })
+
+  test('fulfillWithValue should infer return value', () => {
+    // https://github.com/reduxjs/redux-toolkit/issues/2886
+
+    const initialState = {
+      loading: false,
+      obj: { magic: '' },
+    }
+
+    const getObj = createAsyncThunk(
+      'slice/getObj',
+      async (_: any, { fulfillWithValue, rejectWithValue }) => {
+        try {
+          return fulfillWithValue({ magic: 'object' })
+        } catch (rejected: any) {
+          return rejectWithValue(rejected?.response?.error || rejected)
+        }
+      },
+    )
+
+    createSlice({
+      name: 'slice',
+      initialState,
+      reducers: {},
+      extraReducers: (builder) => {
+        builder.addCase(getObj.fulfilled, (state, action) => {
+          expectTypeOf(action.payload).toEqualTypeOf<{ magic: string }>()
+        })
+      },
+    })
+  })
+
+  test('meta return values', () => {
+    // return values
+    createAsyncThunk<'ret', void, {}>('test', (_, api) => 'ret' as const)
+    createAsyncThunk<'ret', void, {}>('test', async (_, api) => 'ret' as const)
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>('test', (_, api) =>
+      api.fulfillWithValue('ret' as const, ''),
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test',
+      async (_, api) => api.fulfillWithValue('ret' as const, ''),
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test',
+      // @ts-expect-error has to be a fulfilledWithValue call
+      (_, api) => 'ret' as const,
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test',
+      // @ts-expect-error has to be a fulfilledWithValue call
+      async (_, api) => 'ret' as const,
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test', // @ts-expect-error should only allow returning with 'test'
+      (_, api) => api.fulfillWithValue(5, ''),
+    )
+    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(
+      'test', // @ts-expect-error should only allow returning with 'test'
+      async (_, api) => api.fulfillWithValue(5, ''),
+    )
+
+    // reject values
+    createAsyncThunk<'ret', void, { rejectValue: string }>('test', (_, api) =>
+      api.rejectWithValue('ret'),
+    )
+    createAsyncThunk<'ret', void, { rejectValue: string }>(
+      'test',
+      async (_, api) => api.rejectWithValue('ret'),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >('test', (_, api) => api.rejectWithValue('ret', 5))
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >('test', async (_, api) => api.rejectWithValue('ret', 5))
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >('test', (_, api) => api.rejectWithValue('ret', 5))
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectedMeta type
+      (_, api) => api.rejectWithValue('ret', ''),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectedMeta type
+      async (_, api) => api.rejectWithValue('ret', ''),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectValue type
+      (_, api) => api.rejectWithValue(5, ''),
+    )
+    createAsyncThunk<
+      'ret',
+      void,
+      { rejectValue: string; rejectedMeta: number }
+    >(
+      'test',
+      // @ts-expect-error wrong rejectValue type
+      async (_, api) => api.rejectWithValue(5, ''),
+    )
+  })
+
+  test('usage with config override generic', () => {
+    const typedCAT = createAsyncThunk.withTypes<{
+      state: RootState
+      dispatch: AppDispatch
+      rejectValue: string
+      extra: { s: string; n: number }
+    }>()
+
+    // inferred usage
+    const thunk = typedCAT('foo', (arg: number, api) => {
+      // correct getState Type
+      const test1: number = api.getState().foo.value
+      // correct dispatch type
+      const test2: number = api.dispatch((dispatch, getState) => {
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
+        >()
+
+        expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()
+
+        return getState().foo.value
+      })
+
+      // correct extra type
+      const { s, n } = api.extra
+
+      expectTypeOf(s).toBeString()
+
+      expectTypeOf(n).toBeNumber()
+
+      if (1 < 2)
+        // @ts-expect-error
+        return api.rejectWithValue(5)
+      if (1 < 2) return api.rejectWithValue('test')
+      return test1 + test2
+    })
+
+    // usage with two generics
+    const thunk2 = typedCAT<number, string>('foo', (arg, api) => {
+      expectTypeOf(arg).toBeString()
+
+      // correct getState Type
+      const test1: number = api.getState().foo.value
+      // correct dispatch type
+      const test2: number = api.dispatch((dispatch, getState) => {
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
+        >()
+
+        expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()
+
+        return getState().foo.value
+      })
+      // correct extra type
+      const { s, n } = api.extra
+
+      expectTypeOf(s).toBeString()
+
+      expectTypeOf(n).toBeNumber()
+
+      if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith('test')
+
+      expectTypeOf(api.rejectWithValue).parameter(0).not.toBeNumber()
+
+      expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[string]>()
+
+      return api.rejectWithValue('test')
+    })
+
+    // usage with config override generic
+    const thunk3 = typedCAT<number, string, { rejectValue: number }>(
+      'foo',
+      (arg, api) => {
+        expectTypeOf(arg).toBeString()
+
+        // correct getState Type
+        const test1: number = api.getState().foo.value
+        // correct dispatch type
+        const test2: number = api.dispatch((dispatch, getState) => {
+          expectTypeOf(dispatch).toEqualTypeOf<
+            ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>
+          >()
+
+          expectTypeOf(getState).toEqualTypeOf<
+            () => { foo: { value: number } }
+          >()
+
+          return getState().foo.value
+        })
+        // correct extra type
+        const { s, n } = api.extra
+
+        expectTypeOf(s).toBeString()
+
+        expectTypeOf(n).toBeNumber()
+
+        if (1 < 2) return api.rejectWithValue(5)
+        if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith(5)
+
+        expectTypeOf(api.rejectWithValue).parameter(0).not.toBeString()
+
+        expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[number]>()
+
+        return api.rejectWithValue(5)
+      },
+    )
+
+    const slice = createSlice({
+      name: 'foo',
+      initialState: { value: 0 },
+      reducers: {},
+      extraReducers(builder) {
+        builder
+          .addCase(thunk.fulfilled, (state, action) => {
+            state.value += action.payload
+          })
+          .addCase(thunk.rejected, (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
+          })
+          .addCase(thunk2.fulfilled, (state, action) => {
+            state.value += action.payload
+          })
+          .addCase(thunk2.rejected, (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
+          })
+          .addCase(thunk3.fulfilled, (state, action) => {
+            state.value += action.payload
+          })
+          .addCase(thunk3.rejected, (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<number | undefined>()
+          })
+      },
+    })
+
+    const store = configureStore({
+      reducer: {
+        foo: slice.reducer,
+      },
+    })
+
+    type RootState = ReturnType<typeof store.getState>
+    type AppDispatch = typeof store.dispatch
+  })
+
+  test('rejectedMeta', async () => {
+    const getNewStore = () =>
+      configureStore({
+        reducer(actions = [], action) {
+          return [...actions, action]
+        },
+      })
+
+    const store = getNewStore()
+
+    const fulfilledThunk = createAsyncThunk<
+      string,
+      string,
+      { rejectedMeta: { extraProp: string } }
+    >('test', (arg: string, { rejectWithValue }) => {
+      return rejectWithValue('damn!', { extraProp: 'baz' })
+    })
+
+    const promise = store.dispatch(fulfilledThunk('testArg'))
+
+    const ret = await promise
+
+    if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {
+      expectTypeOf(ret.meta.extraProp).toBeString()
+    } else {
+      // could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case
+      expectTypeOf(ret.meta).not.toHaveProperty('extraProp')
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createAsyncThunk.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1045 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { delay, promiseWithResolvers } from '@internal/utils'
+import type { CreateAsyncThunkFunction, UnknownAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createAsyncThunk,
+  createReducer,
+  miniSerializeError,
+  unwrapResult,
+} from '@reduxjs/toolkit'
+
+declare global {
+  interface Window {
+    AbortController: AbortController
+  }
+}
+
+describe('createAsyncThunk', () => {
+  it('creates the action types', () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+
+    expect(thunkActionCreator.fulfilled.type).toBe('testType/fulfilled')
+    expect(thunkActionCreator.pending.type).toBe('testType/pending')
+    expect(thunkActionCreator.rejected.type).toBe('testType/rejected')
+  })
+
+  it('exposes the typePrefix it was created with', () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+
+    expect(thunkActionCreator.typePrefix).toBe('testType')
+  })
+
+  it('includes a settled matcher', () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+    expect(thunkActionCreator.settled).toEqual(expect.any(Function))
+    expect(thunkActionCreator.settled(thunkActionCreator.pending(''))).toBe(
+      false,
+    )
+    expect(
+      thunkActionCreator.settled(thunkActionCreator.rejected(null, '')),
+    ).toBe(true)
+    expect(
+      thunkActionCreator.settled(thunkActionCreator.fulfilled(42, '')),
+    ).toBe(true)
+  })
+
+  it('works without passing arguments to the payload creator', async () => {
+    const thunkActionCreator = createAsyncThunk('testType', async () => 42)
+
+    let timesReducerCalled = 0
+
+    const reducer = () => {
+      timesReducerCalled++
+    }
+
+    const store = configureStore({
+      reducer,
+    })
+
+    // reset from however many times the store called it
+    timesReducerCalled = 0
+
+    await store.dispatch(thunkActionCreator())
+
+    expect(timesReducerCalled).toBe(2)
+  })
+
+  it('accepts arguments and dispatches the actions on resolve', async () => {
+    const dispatch = vi.fn()
+
+    let passedArg: any
+
+    const result = 42
+    const args = 123
+    let generatedRequestId = ''
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (arg: number, { requestId }) => {
+        passedArg = arg
+        generatedRequestId = requestId
+        return result
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    const thunkPromise = thunkFunction(dispatch, () => {}, undefined)
+
+    expect(thunkPromise.requestId).toBe(generatedRequestId)
+    expect(thunkPromise.arg).toBe(args)
+
+    await thunkPromise
+
+    expect(passedArg).toBe(args)
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      2,
+      thunkActionCreator.fulfilled(result, generatedRequestId, args),
+    )
+  })
+
+  it('accepts arguments and dispatches the actions on reject', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const error = new Error('Panic!')
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId }) => {
+        generatedRequestId = requestId
+        throw error
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual(miniSerializeError(error))
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches an empty error when throwing a random object without serializedError properties', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorObject = { wny: 'dothis' }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId }) => {
+        generatedRequestId = requestId
+        throw errorObject
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual({})
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches an action with a formatted error when throwing an object with known error keys', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorObject = {
+      name: 'Custom thrown error',
+      message: 'This is not necessary',
+      code: '400',
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId }) => {
+        generatedRequestId = requestId
+        throw errorObject
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual(miniSerializeError(errorObject))
+    expect(Object.keys(errorAction.error)).not.toContain('stack')
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches a rejected action with a customized payload when a user returns rejectWithValue()', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorPayload = {
+      errorMessage:
+        'I am a fake server-provided 400 payload with validation details',
+      errors: [
+        { field_one: 'Must be a string' },
+        { field_two: 'Must be a number' },
+      ],
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId, rejectWithValue }) => {
+        generatedRequestId = requestId
+
+        return rejectWithValue(errorPayload)
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+
+    expect(errorAction.error.message).toEqual('Rejected')
+    expect(errorAction.payload).toBe(errorPayload)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches a rejected action with a customized payload when a user throws rejectWithValue()', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const errorPayload = {
+      errorMessage:
+        'I am a fake server-provided 400 payload with validation details',
+      errors: [
+        { field_one: 'Must be a string' },
+        { field_two: 'Must be a number' },
+      ],
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId, rejectWithValue }) => {
+        generatedRequestId = requestId
+
+        throw rejectWithValue(errorPayload)
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+
+    expect(errorAction.error.message).toEqual('Rejected')
+    expect(errorAction.payload).toBe(errorPayload)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+
+  it('dispatches a rejected action with a miniSerializeError when rejectWithValue conditions are not satisfied', async () => {
+    const dispatch = vi.fn()
+
+    const args = 123
+    let generatedRequestId = ''
+
+    const error = new Error('Panic!')
+
+    const errorPayload = {
+      errorMessage:
+        'I am a fake server-provided 400 payload with validation details',
+      errors: [
+        { field_one: 'Must be a string' },
+        { field_two: 'Must be a number' },
+      ],
+    }
+
+    const thunkActionCreator = createAsyncThunk(
+      'testType',
+      async (args: number, { requestId, rejectWithValue }) => {
+        generatedRequestId = requestId
+
+        try {
+          throw error
+        } catch (err) {
+          if (!(err as any).response) {
+            throw err
+          }
+          return rejectWithValue(errorPayload)
+        }
+      },
+    )
+
+    const thunkFunction = thunkActionCreator(args)
+
+    try {
+      await thunkFunction(dispatch, () => {}, undefined)
+    } catch (e) {}
+
+    expect(dispatch).toHaveBeenNthCalledWith(
+      1,
+      thunkActionCreator.pending(generatedRequestId, args),
+    )
+
+    expect(dispatch).toHaveBeenCalledTimes(2)
+
+    // Have to check the bits of the action separately since the error was processed
+    const errorAction = dispatch.mock.calls[1][0]
+    expect(errorAction.error).toEqual(miniSerializeError(error))
+    expect(errorAction.payload).toEqual(undefined)
+    expect(errorAction.meta.requestId).toBe(generatedRequestId)
+    expect(errorAction.meta.arg).toBe(args)
+  })
+})
+
+describe('createAsyncThunk with abortController', () => {
+  const asyncThunk = createAsyncThunk(
+    'test',
+    function abortablePayloadCreator(_: any, { signal }) {
+      return new Promise((resolve, reject) => {
+        if (signal.aborted) {
+          reject(
+            new DOMException(
+              'This should never be reached as it should already be handled.',
+              'AbortError',
+            ),
+          )
+        }
+        signal.addEventListener('abort', () => {
+          reject(new DOMException('Was aborted while running', 'AbortError'))
+        })
+        setTimeout(resolve, 100)
+      })
+    },
+  )
+
+  let store = configureStore({
+    reducer(store: UnknownAction[] = []) {
+      return store
+    },
+  })
+
+  beforeEach(() => {
+    store = configureStore({
+      reducer(store: UnknownAction[] = [], action) {
+        return [...store, action]
+      },
+    })
+  })
+
+  test('normal usage', async () => {
+    await store.dispatch(asyncThunk({}))
+    expect(store.getState()).toEqual([
+      expect.any(Object),
+      expect.objectContaining({ type: 'test/pending' }),
+      expect.objectContaining({ type: 'test/fulfilled' }),
+    ])
+  })
+
+  test('abort after dispatch', async () => {
+    const promise = store.dispatch(asyncThunk({}))
+    promise.abort('AbortReason')
+    const result = await promise
+    const expectedAbortedAction = {
+      type: 'test/rejected',
+      error: {
+        message: 'AbortReason',
+        name: 'AbortError',
+      },
+      meta: { aborted: true, requestId: promise.requestId },
+    }
+
+    // abortedAction with reason is dispatched after test/pending is dispatched
+    expect(store.getState()).toMatchObject([
+      {},
+      { type: 'test/pending' },
+      expectedAbortedAction,
+    ])
+
+    // same abortedAction is returned, but with the AbortError from the abortablePayloadCreator
+    expect(result).toMatchObject(expectedAbortedAction)
+
+    // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator
+    expect(() => unwrapResult(result)).toThrowError(
+      expect.objectContaining(expectedAbortedAction.error),
+    )
+  })
+
+  test('even when the payloadCreator does not directly support the signal, no further actions are dispatched', async () => {
+    const unawareAsyncThunk = createAsyncThunk('unaware', async () => {
+      await new Promise((resolve) => setTimeout(resolve, 100))
+      return 'finished'
+    })
+
+    const promise = store.dispatch(unawareAsyncThunk())
+    promise.abort('AbortReason')
+    const result = await promise
+
+    const expectedAbortedAction = {
+      type: 'unaware/rejected',
+      error: {
+        message: 'AbortReason',
+        name: 'AbortError',
+      },
+    }
+
+    // abortedAction with reason is dispatched after test/pending is dispatched
+    expect(store.getState()).toEqual([
+      expect.any(Object),
+      expect.objectContaining({ type: 'unaware/pending' }),
+      expect.objectContaining(expectedAbortedAction),
+    ])
+
+    // same abortedAction is returned, but with the AbortError from the abortablePayloadCreator
+    expect(result).toMatchObject(expectedAbortedAction)
+
+    // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator
+    expect(() => unwrapResult(result)).toThrowError(
+      expect.objectContaining(expectedAbortedAction.error),
+    )
+  })
+
+  test('dispatch(asyncThunk) returns on abort and does not wait for the promiseProvider to finish', async () => {
+    let running = false
+    const longRunningAsyncThunk = createAsyncThunk('longRunning', async () => {
+      running = true
+      await new Promise((resolve) => setTimeout(resolve, 30000))
+      running = false
+    })
+
+    const promise = store.dispatch(longRunningAsyncThunk())
+    expect(running).toBeTruthy()
+    promise.abort()
+    const result = await promise
+    expect(running).toBeTruthy()
+    expect(result).toMatchObject({
+      type: 'longRunning/rejected',
+      error: { message: 'Aborted', name: 'AbortError' },
+      meta: { aborted: true },
+    })
+  })
+
+  describe('behavior with missing AbortController', () => {
+    let keepAbortController: (typeof window)['AbortController']
+    let freshlyLoadedModule: typeof import('../createAsyncThunk')
+
+    beforeEach(async () => {
+      keepAbortController = window.AbortController
+      delete (window as any).AbortController
+      vi.resetModules()
+      freshlyLoadedModule = await import('../createAsyncThunk')
+      vi.stubEnv('NODE_ENV', 'development')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+      vi.clearAllMocks()
+      vi.stubGlobal('AbortController', keepAbortController)
+      vi.resetModules()
+    })
+
+    test('calling a thunk made with createAsyncThunk should fail if no global abortController is not available', async () => {
+      const longRunningAsyncThunk = freshlyLoadedModule.createAsyncThunk(
+        'longRunning',
+        async () => {
+          await new Promise((resolve) => setTimeout(resolve, 30000))
+        },
+      )
+
+      expect(longRunningAsyncThunk()).toThrow('AbortController is not defined')
+    })
+  })
+})
+
+test('non-serializable arguments are ignored by serializableStateInvariantMiddleware', async () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+  const nonSerializableValue = new Map()
+  const asyncThunk = createAsyncThunk('test', (arg: Map<any, any>) => {})
+
+  configureStore({
+    reducer: () => 0,
+  }).dispatch(asyncThunk(nonSerializableValue))
+
+  expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+  consoleErrorSpy.mockRestore()
+})
+
+describe('conditional skipping of asyncThunks', () => {
+  const arg = {}
+  const getState = vi.fn(() => ({}))
+  const dispatch = vi.fn((x: any) => x)
+  const payloadCreator = vi.fn((x: typeof arg) => 10)
+  const condition = vi.fn(() => false)
+  const extra = {}
+
+  beforeEach(() => {
+    getState.mockClear()
+    dispatch.mockClear()
+    payloadCreator.mockClear()
+    condition.mockClear()
+  })
+
+  test('returning false from condition skips payloadCreator and returns a rejected action', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const result = await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalled()
+    expect(payloadCreator).not.toHaveBeenCalled()
+    expect(asyncThunk.rejected.match(result)).toBe(true)
+    expect((result as any).meta.condition).toBe(true)
+  })
+
+  test('return falsy from condition does not skip payload creator', async () => {
+    // Override TS's expectation that this is a boolean
+    condition.mockReturnValueOnce(undefined as unknown as boolean)
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const result = await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalled()
+    expect(payloadCreator).toHaveBeenCalled()
+    expect(asyncThunk.fulfilled.match(result)).toBe(true)
+    expect(result.payload).toBe(10)
+  })
+
+  test('returning true from condition executes payloadCreator', async () => {
+    condition.mockReturnValueOnce(true)
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const result = await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalled()
+    expect(payloadCreator).toHaveBeenCalled()
+    expect(asyncThunk.fulfilled.match(result)).toBe(true)
+    expect(result.payload).toBe(10)
+  })
+
+  test('condition is called with arg, getState and extra', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(condition).toHaveBeenCalledOnce()
+    expect(condition).toHaveBeenLastCalledWith(
+      arg,
+      expect.objectContaining({ getState, extra }),
+    )
+  })
+
+  test('pending is dispatched synchronously if condition is synchronous', async () => {
+    const condition = () => true
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    const thunkCallPromise = asyncThunk(arg)(dispatch, getState, extra)
+    expect(dispatch).toHaveBeenCalledOnce()
+    await thunkCallPromise
+    expect(dispatch).toHaveBeenCalledTimes(2)
+  })
+
+  test('async condition', async () => {
+    const condition = () => Promise.resolve(false)
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+    expect(dispatch).not.toHaveBeenCalled()
+  })
+
+  test('async condition with rejected promise', async () => {
+    const condition = () => Promise.reject()
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+    expect(dispatch).toHaveBeenCalledOnce()
+    expect(dispatch).toHaveBeenLastCalledWith(
+      expect.objectContaining({ type: 'test/rejected' }),
+    )
+  })
+
+  test('async condition with AbortController signal first', async () => {
+    const condition = async () => {
+      await delay(25)
+      return true
+    }
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+
+    try {
+      const thunkPromise = asyncThunk(arg)(dispatch, getState, extra)
+      thunkPromise.abort()
+      await thunkPromise
+    } catch (err) {}
+    expect(dispatch).not.toHaveBeenCalled()
+  })
+
+  test('rejected action is not dispatched by default', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })
+    await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(dispatch).not.toHaveBeenCalled()
+  })
+
+  test('does not fail when attempting to abort a canceled promise', async () => {
+    const asyncPayloadCreator = vi.fn(async (x: typeof arg) => {
+      await delay(200)
+      return 10
+    })
+
+    const asyncThunk = createAsyncThunk('test', asyncPayloadCreator, {
+      condition,
+    })
+    const promise = asyncThunk(arg)(dispatch, getState, extra)
+    promise.abort(
+      `If the promise was 1. somehow canceled, 2. in a 'started' state and 3. we attempted to abort, this would crash the tests`,
+    )
+  })
+
+  test('rejected action can be dispatched via option', async () => {
+    const asyncThunk = createAsyncThunk('test', payloadCreator, {
+      condition,
+      dispatchConditionRejection: true,
+    })
+    await asyncThunk(arg)(dispatch, getState, extra)
+
+    expect(dispatch).toHaveBeenCalledOnce()
+    expect(dispatch).toHaveBeenLastCalledWith(
+      expect.objectContaining({
+        error: {
+          message: 'Aborted due to condition callback returning false.',
+          name: 'ConditionError',
+        },
+        meta: {
+          aborted: false,
+          arg,
+          rejectedWithValue: false,
+          condition: true,
+          requestId: expect.stringContaining(''),
+          requestStatus: 'rejected',
+        },
+        payload: undefined,
+        type: 'test/rejected',
+      }),
+    )
+  })
+})
+
+test('serializeError implementation', async () => {
+  function serializeError() {
+    return 'serialized!'
+  }
+  const errorObject = 'something else!'
+
+  const store = configureStore({
+    reducer: (state = [], action) => [...state, action],
+  })
+
+  const asyncThunk = createAsyncThunk<
+    unknown,
+    void,
+    { serializedErrorType: string }
+  >('test', () => Promise.reject(errorObject), { serializeError })
+  const rejected = await store.dispatch(asyncThunk())
+  if (!asyncThunk.rejected.match(rejected)) {
+    throw new Error()
+  }
+
+  const expectation = {
+    type: 'test/rejected',
+    payload: undefined,
+    error: 'serialized!',
+    meta: expect.any(Object),
+  }
+  expect(rejected).toEqual(expectation)
+  expect(store.getState()[2]).toEqual(expectation)
+  expect(rejected.error).not.toEqual(miniSerializeError(errorObject))
+})
+
+describe('unwrapResult', () => {
+  const getState = vi.fn(() => ({}))
+  const dispatch = vi.fn((x: any) => x)
+  const extra = {}
+  test('fulfilled case', async () => {
+    const asyncThunk = createAsyncThunk('test', () => {
+      return 'fulfilled!' as const
+    })
+
+    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(
+      unwrapResult,
+    )
+
+    await expect(unwrapPromise).resolves.toBe('fulfilled!')
+
+    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)
+    const res = await unwrapPromise2.unwrap()
+    expect(res).toBe('fulfilled!')
+  })
+  test('error case', async () => {
+    const error = new Error('Panic!')
+    const asyncThunk = createAsyncThunk('test', () => {
+      throw error
+    })
+
+    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(
+      unwrapResult,
+    )
+
+    await expect(unwrapPromise).rejects.toEqual(miniSerializeError(error))
+
+    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)
+    await expect(unwrapPromise2.unwrap()).rejects.toEqual(
+      miniSerializeError(error),
+    )
+  })
+  test('rejectWithValue case', async () => {
+    const asyncThunk = createAsyncThunk('test', (_, { rejectWithValue }) => {
+      return rejectWithValue('rejectWithValue!')
+    })
+
+    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(
+      unwrapResult,
+    )
+
+    await expect(unwrapPromise).rejects.toBe('rejectWithValue!')
+
+    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)
+    await expect(unwrapPromise2.unwrap()).rejects.toBe('rejectWithValue!')
+  })
+})
+
+describe('idGenerator option', () => {
+  const getState = () => ({})
+  const dispatch = (x: any) => x
+  const extra = {}
+
+  test('idGenerator implementation - can customizes how request IDs are generated', async () => {
+    function makeFakeIdGenerator() {
+      let id = 0
+      return vi.fn(() => {
+        id++
+        return `fake-random-id-${id}`
+      })
+    }
+
+    let generatedRequestId = ''
+
+    const idGenerator = makeFakeIdGenerator()
+    const asyncThunk = createAsyncThunk(
+      'test',
+      async (args: void, { requestId }) => {
+        generatedRequestId = requestId
+      },
+      { idGenerator },
+    )
+
+    // dispatching the thunks should be using the custom id generator
+    const promise0 = asyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual('fake-random-id-1')
+    expect(promise0.requestId).toEqual('fake-random-id-1')
+    expect((await promise0).meta.requestId).toEqual('fake-random-id-1')
+
+    const promise1 = asyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual('fake-random-id-2')
+    expect(promise1.requestId).toEqual('fake-random-id-2')
+    expect((await promise1).meta.requestId).toEqual('fake-random-id-2')
+
+    const promise2 = asyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual('fake-random-id-3')
+    expect(promise2.requestId).toEqual('fake-random-id-3')
+    expect((await promise2).meta.requestId).toEqual('fake-random-id-3')
+
+    generatedRequestId = ''
+    const defaultAsyncThunk = createAsyncThunk(
+      'test',
+      async (args: void, { requestId }) => {
+        generatedRequestId = requestId
+      },
+    )
+    // dispatching the default options thunk should still generate an id,
+    // but not using the custom id generator
+    const promise3 = defaultAsyncThunk()(dispatch, getState, extra)
+    expect(generatedRequestId).toEqual(promise3.requestId)
+    expect(promise3.requestId).not.toEqual('')
+    expect(promise3.requestId).not.toEqual(
+      expect.stringContaining('fake-random-id'),
+    )
+    expect((await promise3).meta.requestId).not.toEqual(
+      expect.stringContaining('fake-fandom-id'),
+    )
+  })
+
+  test('idGenerator should be called with thunkArg', async () => {
+    const customIdGenerator = vi.fn((seed) => `fake-unique-random-id-${seed}`)
+    let generatedRequestId = ''
+    const asyncThunk = createAsyncThunk(
+      'test',
+      async (args: any, { requestId }) => {
+        generatedRequestId = requestId
+      },
+      { idGenerator: customIdGenerator },
+    )
+
+    const thunkArg = 1
+    const expected = 'fake-unique-random-id-1'
+    const asyncThunkPromise = asyncThunk(thunkArg)(dispatch, getState, extra)
+
+    expect(customIdGenerator).toHaveBeenCalledWith(thunkArg)
+    expect(asyncThunkPromise.requestId).toEqual(expected)
+    expect((await asyncThunkPromise).meta.requestId).toEqual(expected)
+  })
+})
+
+test('`condition` will see state changes from a synchronously invoked asyncThunk', () => {
+  type State = ReturnType<typeof store.getState>
+  const onStart = vi.fn()
+  const asyncThunk = createAsyncThunk<
+    void,
+    { force?: boolean },
+    { state: State }
+  >('test', onStart, {
+    condition({ force }, { getState }) {
+      return force || !getState().started
+    },
+  })
+  const store = configureStore({
+    reducer: createReducer({ started: false }, (builder) => {
+      builder.addCase(asyncThunk.pending, (state) => {
+        state.started = true
+      })
+    }),
+  })
+
+  store.dispatch(asyncThunk({ force: false }))
+  expect(onStart).toHaveBeenCalledOnce()
+  store.dispatch(asyncThunk({ force: false }))
+  expect(onStart).toHaveBeenCalledOnce()
+  store.dispatch(asyncThunk({ force: true }))
+  expect(onStart).toHaveBeenCalledTimes(2)
+})
+
+const getNewStore = () =>
+  configureStore({
+    reducer(actions: UnknownAction[] = [], action) {
+      return [...actions, action]
+    },
+  })
+
+describe('meta', () => {
+  let store = getNewStore()
+
+  beforeEach(() => {
+    store = getNewStore()
+  })
+
+  test('pendingMeta', () => {
+    const pendingThunk = createAsyncThunk('test', (arg: string) => {}, {
+      getPendingMeta({ arg, requestId }) {
+        expect(arg).toBe('testArg')
+        expect(requestId).toEqual(expect.any(String))
+        return { extraProp: 'foo' }
+      },
+    })
+    const ret = store.dispatch(pendingThunk('testArg'))
+    expect(store.getState()[1]).toEqual({
+      meta: {
+        arg: 'testArg',
+        extraProp: 'foo',
+        requestId: ret.requestId,
+        requestStatus: 'pending',
+      },
+      payload: undefined,
+      type: 'test/pending',
+    })
+  })
+
+  test('fulfilledMeta', async () => {
+    const fulfilledThunk = createAsyncThunk<
+      string,
+      string,
+      { fulfilledMeta: { extraProp: string } }
+    >('test', (arg: string, { fulfillWithValue }) => {
+      return fulfillWithValue('hooray!', { extraProp: 'bar' })
+    })
+    const ret = store.dispatch(fulfilledThunk('testArg'))
+    expect(await ret).toEqual({
+      meta: {
+        arg: 'testArg',
+        extraProp: 'bar',
+        requestId: ret.requestId,
+        requestStatus: 'fulfilled',
+      },
+      payload: 'hooray!',
+      type: 'test/fulfilled',
+    })
+  })
+
+  test('rejectedMeta', async () => {
+    const fulfilledThunk = createAsyncThunk<
+      string,
+      string,
+      { rejectedMeta: { extraProp: string } }
+    >('test', (arg: string, { rejectWithValue }) => {
+      return rejectWithValue('damn!', { extraProp: 'baz' })
+    })
+    const promise = store.dispatch(fulfilledThunk('testArg'))
+    const ret = await promise
+    expect(ret).toEqual({
+      meta: {
+        arg: 'testArg',
+        extraProp: 'baz',
+        requestId: promise.requestId,
+        requestStatus: 'rejected',
+        rejectedWithValue: true,
+        aborted: false,
+        condition: false,
+      },
+      error: { message: 'Rejected' },
+      payload: 'damn!',
+      type: 'test/rejected',
+    })
+
+    if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {
+    } else {
+      // could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case
+      // @ts-expect-error
+      ret.meta.extraProp
+    }
+  })
+
+  test('typed createAsyncThunk.withTypes', () => {
+    const typedCAT = createAsyncThunk.withTypes<{
+      state: { s: string }
+      rejectValue: string
+      extra: { s: string; n: number }
+    }>()
+    const thunk = typedCAT('a', () => 'b')
+    const expectFunction = expect.any(Function)
+    expect(thunk.fulfilled).toEqual(expectFunction)
+    expect(thunk.pending).toEqual(expectFunction)
+    expect(thunk.rejected).toEqual(expectFunction)
+    expect(thunk.settled).toEqual(expectFunction)
+    expect(thunk.fulfilled.type).toBe('a/fulfilled')
+  })
+  test('createAsyncThunkWrapper using CreateAsyncThunkFunction', async () => {
+    const customSerializeError = () => 'serialized!'
+    const createAppAsyncThunk: CreateAsyncThunkFunction<{
+      serializedErrorType: ReturnType<typeof customSerializeError>
+    }> = (prefix: string, payloadCreator: any, options: any) =>
+      createAsyncThunk(prefix, payloadCreator, {
+        ...options,
+        serializeError: customSerializeError,
+      }) as any
+
+    const asyncThunk = createAppAsyncThunk('test', async () => {
+      throw new Error('Panic!')
+    })
+
+    const promise = store.dispatch(asyncThunk())
+    const result = await promise
+    if (!asyncThunk.rejected.match(result)) {
+      throw new Error('should have thrown')
+    }
+    expect(result.error).toEqual('serialized!')
+  })
+})
+
+describe('dispatch config', () => {
+  let store = getNewStore()
+
+  beforeEach(() => {
+    store = getNewStore()
+  })
+  test('accepts external signal', async () => {
+    const asyncThunk = createAsyncThunk('test', async (_: void, { signal }) => {
+      signal.throwIfAborted()
+      const { promise, reject } = promiseWithResolvers<never>()
+      signal.addEventListener('abort', () => reject(signal.reason))
+      return promise
+    })
+
+    const abortController = new AbortController()
+    const promise = store.dispatch(
+      asyncThunk(undefined, { signal: abortController.signal }),
+    )
+    abortController.abort()
+    await expect(promise.unwrap()).rejects.toThrow(
+      'External signal was aborted',
+    )
+  })
+  test('handles already aborted external signal', async () => {
+    const asyncThunk = createAsyncThunk('test', async (_: void, { signal }) => {
+      signal.throwIfAborted()
+      const { promise, reject } = promiseWithResolvers<never>()
+      signal.addEventListener('abort', () => reject(signal.reason))
+      return promise
+    })
+
+    const signal = AbortSignal.abort()
+    const promise = store.dispatch(asyncThunk(undefined, { signal }))
+    await expect(promise.unwrap()).rejects.toThrow(
+      'Aborted due to condition callback returning false.',
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,43 @@
+import { createDraftSafeSelector, createSelector } from '@reduxjs/toolkit'
+import { produce } from 'immer'
+
+type State = { value: number }
+const selectSelf = (state: State) => state
+
+test('handles normal values correctly', () => {
+  const unsafeSelector = createSelector(selectSelf, (x) => x.value)
+  const draftSafeSelector = createDraftSafeSelector(selectSelf, (x) => x.value)
+
+  let state = { value: 1 }
+  expect(unsafeSelector(state)).toBe(1)
+  expect(draftSafeSelector(state)).toBe(1)
+  expect(draftSafeSelector).toHaveProperty('resultFunc')
+  expect(draftSafeSelector).toHaveProperty('memoizedResultFunc')
+  expect(draftSafeSelector).toHaveProperty('lastResult')
+  expect(draftSafeSelector).toHaveProperty('dependencies')
+  expect(draftSafeSelector).toHaveProperty('recomputations')
+  expect(draftSafeSelector).toHaveProperty('resetRecomputations')
+  expect(draftSafeSelector).toHaveProperty('clearCache')
+
+  state = { value: 2 }
+  expect(unsafeSelector(state)).toBe(2)
+  expect(draftSafeSelector(state)).toBe(2)
+})
+
+test('handles drafts correctly', () => {
+  const unsafeSelector = createSelector(selectSelf, (state) => state.value)
+  const draftSafeSelector = createDraftSafeSelector(
+    selectSelf,
+    (state) => state.value,
+  )
+
+  produce({ value: 1 }, (state) => {
+    expect(unsafeSelector(state)).toBe(1)
+    expect(draftSafeSelector(state)).toBe(1)
+
+    state.value = 2
+
+    expect(unsafeSelector(state)).toBe(1)
+    expect(draftSafeSelector(state)).toBe(2)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,49 @@
+import { createDraftSafeSelector } from '@reduxjs/toolkit'
+
+interface Todo {
+  id: number
+  completed: boolean
+}
+
+interface Alert {
+  id: number
+  read: boolean
+}
+
+interface RootState {
+  todos: Todo[]
+  alerts: Alert[]
+}
+
+const rootState: RootState = {
+  todos: [
+    { id: 0, completed: false },
+    { id: 1, completed: false },
+  ],
+  alerts: [
+    { id: 0, read: false },
+    { id: 1, read: false },
+  ],
+}
+
+describe(createDraftSafeSelector.withTypes, () => {
+  const createTypedDraftSafeSelector =
+    createDraftSafeSelector.withTypes<RootState>()
+
+  test('should return createDraftSafeSelector', () => {
+    expect(createTypedDraftSafeSelector.withTypes).toEqual(expect.any(Function))
+
+    expect(createTypedDraftSafeSelector.withTypes().withTypes).toEqual(
+      expect.any(Function),
+    )
+
+    expect(createTypedDraftSafeSelector).toBe(createDraftSafeSelector)
+
+    const selectTodoIds = createTypedDraftSafeSelector(
+      [(state) => state.todos],
+      (todos) => todos.map(({ id }) => id),
+    )
+
+    expect(selectTodoIds(rootState)).to.be.an('array').that.is.not.empty
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createEntityAdapter.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createEntityAdapter.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createEntityAdapter.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,161 @@
+import type {
+  ActionCreatorWithPayload,
+  ActionCreatorWithoutPayload,
+  EntityAdapter,
+  EntityId,
+  EntityStateAdapter,
+  Update,
+} from '@reduxjs/toolkit'
+import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
+
+function extractReducers<T, Id extends EntityId>(
+  adapter: EntityAdapter<T, Id>,
+): EntityStateAdapter<T, Id> {
+  const { selectId, sortComparer, getInitialState, getSelectors, ...rest } =
+    adapter
+  return rest
+}
+
+describe('type tests', () => {
+  test('should be usable in a slice, with all the "reducer-like" functions', () => {
+    type Id = string & { readonly __tag: unique symbol }
+    type Entity = {
+      id: Id
+    }
+    const adapter = createEntityAdapter<Entity>()
+    const slice = createSlice({
+      name: 'test',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        ...extractReducers(adapter),
+      },
+    })
+
+    expectTypeOf(slice.actions.addOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Entity>
+    >()
+
+    expectTypeOf(slice.actions.addMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.setAll).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.removeOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Id>
+    >()
+
+    expectTypeOf(slice.actions.addMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<Entity[] | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.setAll).not.toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Id>>
+    >()
+
+    expectTypeOf(slice.actions.removeOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Id>
+    >()
+
+    expectTypeOf(slice.actions.removeMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Id>>
+    >()
+
+    expectTypeOf(slice.actions.removeMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<EntityId[]>
+    >()
+
+    expectTypeOf(
+      slice.actions.removeAll,
+    ).toMatchTypeOf<ActionCreatorWithoutPayload>()
+
+    expectTypeOf(slice.actions.updateOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Update<Entity, Id>>
+    >()
+
+    expectTypeOf(slice.actions.updateMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<Update<Entity, Id>[]>
+    >()
+
+    expectTypeOf(slice.actions.upsertOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Entity>
+    >()
+
+    expectTypeOf(slice.actions.updateMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Update<Entity, Id>>>
+    >()
+
+    expectTypeOf(slice.actions.upsertOne).toMatchTypeOf<
+      ActionCreatorWithPayload<Entity>
+    >()
+
+    expectTypeOf(slice.actions.upsertMany).toMatchTypeOf<
+      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>
+    >()
+
+    expectTypeOf(slice.actions.upsertMany).not.toMatchTypeOf<
+      ActionCreatorWithPayload<Entity[] | Record<string, Entity>>
+    >()
+  })
+
+  test('should not be able to mix with a different EntityAdapter', () => {
+    type Entity = {
+      id: EntityId
+      value: string
+    }
+    type Entity2 = {
+      id: EntityId
+      value2: string
+    }
+    const adapter = createEntityAdapter<Entity>()
+    const adapter2 = createEntityAdapter<Entity2>()
+    createSlice({
+      name: 'test',
+      initialState: adapter.getInitialState(),
+      reducers: {
+        addOne: adapter.addOne,
+        // @ts-expect-error
+        addOne2: adapter2.addOne,
+      },
+    })
+  })
+
+  test('should be usable in a slice with extra properties', () => {
+    type Entity = { id: EntityId; value: string }
+    const adapter = createEntityAdapter<Entity>()
+    createSlice({
+      name: 'test',
+      initialState: adapter.getInitialState({ extraData: 'test' }),
+      reducers: {
+        addOne: adapter.addOne,
+      },
+    })
+  })
+
+  test('should not be usable in a slice with an unfitting state', () => {
+    type Entity = { id: EntityId; value: string }
+    const adapter = createEntityAdapter<Entity>()
+    createSlice({
+      name: 'test',
+      initialState: { somethingElse: '' },
+      reducers: {
+        // @ts-expect-error
+        addOne: adapter.addOne,
+      },
+    })
+  })
+
+  test('should not be able to create an adapter unless the type has an Id or an idSelector is provided', () => {
+    type Entity = {
+      value: string
+    }
+    // @ts-expect-error
+    const adapter = createEntityAdapter<Entity>()
+    const adapter2: EntityAdapter<Entity, Entity['value']> =
+      createEntityAdapter({
+        selectId: (e: Entity) => e.value,
+      })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createReducer.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createReducer.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createReducer.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,77 @@
+import type { ActionReducerMapBuilder, Reducer } from '@reduxjs/toolkit'
+import { createAction, createReducer } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('createReducer() infers type of returned reducer.', () => {
+    const incrementHandler = (
+      state: number,
+      action: { type: 'increment'; payload: number },
+    ) => state + 1
+
+    const decrementHandler = (
+      state: number,
+      action: { type: 'decrement'; payload: number },
+    ) => state - 1
+
+    const reducer = createReducer(0 as number, (builder) => {
+      builder
+        .addCase('increment', incrementHandler)
+        .addCase('decrement', decrementHandler)
+    })
+
+    expectTypeOf(reducer).toMatchTypeOf<Reducer<number>>()
+
+    expectTypeOf(reducer).not.toMatchTypeOf<Reducer<string>>()
+  })
+
+  test('createReducer() state type can be specified explicitly.', () => {
+    const incrementHandler = (
+      state: number,
+      action: { type: 'increment'; payload: number },
+    ) => state + action.payload
+
+    const decrementHandler = (
+      state: number,
+      action: { type: 'decrement'; payload: number },
+    ) => state - action.payload
+
+    createReducer(0 as number, (builder) => {
+      builder
+        .addCase('increment', incrementHandler)
+        .addCase('decrement', decrementHandler)
+    })
+
+    // @ts-expect-error
+    createReducer<string>(0 as number, (builder) => {
+      expectTypeOf(builder.addCase)
+        .parameter(1)
+        .not.toMatchTypeOf(incrementHandler)
+
+      expectTypeOf(builder.addCase)
+        .parameter(1)
+        .not.toMatchTypeOf(decrementHandler)
+    })
+  })
+
+  test('createReducer() ensures state type is mutable within a case reducer.', () => {
+    const initialState: { readonly counter: number } = { counter: 0 }
+
+    createReducer(initialState, (builder) => {
+      builder.addCase('increment', (state) => {
+        state.counter += 1
+      })
+    })
+  })
+
+  test('builder callback for actionMap', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    const reducer = createReducer(0, (builder) =>
+      expectTypeOf(builder).toEqualTypeOf<ActionReducerMapBuilder<number>>(),
+    )
+
+    expectTypeOf(reducer(0, increment(5))).toBeNumber()
+
+    expectTypeOf(reducer(0, increment(5))).not.toBeString()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,693 @@
+import type {
+  CaseReducer,
+  Draft,
+  PayloadAction,
+  Reducer,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import {
+  createAction,
+  createAsyncThunk,
+  createNextState,
+  createReducer,
+  isPlainObject,
+} from '@reduxjs/toolkit'
+import { waitMs } from './utils/helpers'
+
+interface Todo {
+  text: string
+  completed?: boolean
+}
+
+interface AddTodoPayload {
+  newTodo: Todo
+}
+
+interface ToggleTodoPayload {
+  index: number
+}
+
+type TodoState = Todo[]
+type TodosReducer = Reducer<TodoState, PayloadAction<any>>
+type AddTodoReducer = CaseReducer<
+  TodoState,
+  PayloadAction<AddTodoPayload, 'ADD_TODO'>
+>
+
+type ToggleTodoReducer = CaseReducer<
+  TodoState,
+  PayloadAction<ToggleTodoPayload, 'TOGGLE_TODO'>
+>
+
+type CreateReducer = typeof createReducer
+
+const addTodoThunk = createAsyncThunk('todos/add', (todo: Todo) => todo)
+
+describe('createReducer', () => {
+  describe('given impure reducers with immer', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+
+      // Can safely call state.push() here
+      state.push({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+
+      const todo = state[index]
+      // Can directly modify the todo object
+      todo.completed = !todo.completed
+    }
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    behavesLikeReducer(todosReducer)
+  })
+
+  describe('Deprecation warnings', () => {
+    beforeEach(() => {
+      vi.resetModules()
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    it('Throws an error if the legacy object notation is used', async () => {
+      const { createReducer } = await import('../createReducer')
+      const wrapper = () => {
+        const dummyReducer = (createReducer as CreateReducer)(
+          [] as TodoState,
+          // @ts-ignore
+          {},
+        )
+      }
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createReducer` has been removed/,
+      )
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createReducer` has been removed/,
+      )
+    })
+
+    it('Crashes in production', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+      const { createReducer } = await import('../createReducer')
+      const wrapper = () => {
+        const dummyReducer = (createReducer as CreateReducer)(
+          [] as TodoState,
+          // @ts-ignore
+          {},
+        )
+      }
+
+      expect(wrapper).toThrowError()
+    })
+  })
+
+  describe('Immer in a production environment', () => {
+    beforeEach(() => {
+      vi.resetModules()
+      vi.stubEnv('NODE_ENV', 'production')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    test('Freezes data in production', async () => {
+      const { createReducer } = await import('../createReducer')
+      const addTodo: AddTodoReducer = (state, action) => {
+        const { newTodo } = action.payload
+        state.push({ ...newTodo, completed: false })
+      }
+
+      const toggleTodo: ToggleTodoReducer = (state, action) => {
+        const { index } = action.payload
+        const todo = state[index]
+        todo.completed = !todo.completed
+      }
+
+      const todosReducer = createReducer([] as TodoState, (builder) => {
+        builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+      })
+
+      const result = todosReducer([], {
+        type: 'ADD_TODO',
+        payload: { text: 'Buy milk' },
+      })
+
+      const mutateStateOutsideReducer = () => (result[0].text = 'edited')
+      expect(mutateStateOutsideReducer).toThrowError(
+        'Cannot add property text, object is not extensible',
+      )
+    })
+
+    test('Freezes initial state', () => {
+      const initialState = [{ text: 'Buy milk' }]
+      const todosReducer = createReducer(initialState, () => {})
+      const frozenInitialState = todosReducer(undefined, { type: 'dummy' })
+
+      const mutateStateOutsideReducer = () =>
+        (frozenInitialState[0].text = 'edited')
+      expect(mutateStateOutsideReducer).toThrowError(
+        /Cannot assign to read only property/,
+      )
+    })
+    test('does not throw error if initial state is not draftable', () => {
+      expect(() =>
+        createReducer(new URLSearchParams(), () => {}),
+      ).not.toThrowError()
+    })
+  })
+
+  describe('given pure reducers with immutable updates', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+
+      // Updates the state immutably without relying on immer
+      return state.concat({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+
+      // Updates the todo object immutably withot relying on immer
+      return state.map((todo, i) => {
+        if (i !== index) return todo
+        return { ...todo, completed: !todo.completed }
+      })
+    }
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    behavesLikeReducer(todosReducer)
+  })
+
+  describe('Accepts a lazy state init function to generate initial state', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+      state.push({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+      const todo = state[index]
+      todo.completed = !todo.completed
+    }
+
+    const lazyStateInit = () => [] as TodoState
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    behavesLikeReducer(todosReducer)
+
+    it('Should only call the init function when `undefined` state is passed in', () => {
+      const spy = vi.fn().mockReturnValue(42)
+
+      const dummyReducer = createReducer(spy, () => {})
+      expect(spy).not.toHaveBeenCalled()
+
+      dummyReducer(123, { type: 'dummy' })
+      expect(spy).not.toHaveBeenCalled()
+
+      const initialState = dummyReducer(undefined, { type: 'dummy' })
+      expect(spy).toHaveBeenCalledOnce()
+    })
+  })
+
+  describe('given draft state from immer', () => {
+    const addTodo: AddTodoReducer = (state, action) => {
+      const { newTodo } = action.payload
+
+      // Can safely call state.push() here
+      state.push({ ...newTodo, completed: false })
+    }
+
+    const toggleTodo: ToggleTodoReducer = (state, action) => {
+      const { index } = action.payload
+
+      const todo = state[index]
+      // Can directly modify the todo object
+      todo.completed = !todo.completed
+    }
+
+    const todosReducer = createReducer([] as TodoState, (builder) => {
+      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
+    })
+
+    const wrappedReducer: TodosReducer = (state = [], action) => {
+      return createNextState(state, (draft: Draft<TodoState>) => {
+        todosReducer(draft, action)
+      })
+    }
+
+    behavesLikeReducer(wrappedReducer)
+  })
+
+  describe('builder callback for actionMap', () => {
+    const increment = createAction<number, 'increment'>('increment')
+    const decrement = createAction<number, 'decrement'>('decrement')
+
+    test('can be used with ActionCreators', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder
+          .addCase(increment, (state, action) => state + action.payload)
+          .addCase(decrement, (state, action) => state - action.payload),
+      )
+      expect(reducer(0, increment(5))).toBe(5)
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('can be used with string types', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder
+          .addCase(
+            'increment',
+            (state, action: { type: 'increment'; payload: number }) =>
+              state + action.payload,
+          )
+          .addCase(
+            'decrement',
+            (state, action: { type: 'decrement'; payload: number }) =>
+              state - action.payload,
+          ),
+      )
+      expect(reducer(0, increment(5))).toBe(5)
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('can be used with ActionCreators and string types combined', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder
+          .addCase(increment, (state, action) => state + action.payload)
+          .addCase(
+            'decrement',
+            (state, action: { type: 'decrement'; payload: number }) =>
+              state - action.payload,
+          ),
+      )
+      expect(reducer(0, increment(5))).toBe(5)
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('will throw an error when returning undefined from a non-draftable state', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) => {},
+        ),
+      )
+      expect(() => reducer(5, decrement(5))).toThrowErrorMatchingInlineSnapshot(
+        `[Error: A case reducer on a non-draftable value must not return undefined]`,
+      )
+    })
+    test('allows you to return undefined if the state was null, thus skipping an update', () => {
+      const reducer = createReducer(null as number | null, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) => {
+            if (typeof state === 'number') {
+              return state - action.payload
+            }
+            return undefined
+          },
+        ),
+      )
+      expect(reducer(0, decrement(5))).toBe(-5)
+      expect(reducer(null, decrement(5))).toBe(null)
+    })
+    test('allows you to return null', () => {
+      const reducer = createReducer(0 as number | null, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) => {
+            return null
+          },
+        ),
+      )
+      expect(reducer(5, decrement(5))).toBe(null)
+    })
+    test('allows you to return 0', () => {
+      const reducer = createReducer(0, (builder) =>
+        builder.addCase(
+          'decrement',
+          (state, action: { type: 'decrement'; payload: number }) =>
+            state - action.payload,
+        ),
+      )
+      expect(reducer(5, decrement(5))).toBe(0)
+    })
+    test('will throw if the same type is used twice', () => {
+      expect(() => {
+        createReducer(0, (builder) => {
+          builder
+            .addCase(increment, (state, action) => state + action.payload)
+            .addCase(increment, (state, action) => state + action.payload)
+            .addCase(decrement, (state, action) => state - action.payload)
+        })
+      }).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
+      )
+      expect(() => {
+        createReducer(0, (builder) => {
+          builder
+            .addCase(increment, (state, action) => state + action.payload)
+            .addCase('increment', (state) => state + 1)
+            .addCase(decrement, (state, action) => state - action.payload)
+        })
+      }).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
+      )
+    })
+
+    test('will throw if an empty type is used', () => {
+      const customActionCreator = (payload: number) => ({
+        type: 'custom_action',
+        payload,
+      })
+      customActionCreator.type = ''
+      expect(() => {
+        createReducer(0, (builder) => {
+          builder.addCase(
+            customActionCreator,
+            (state, action) => state + action.payload,
+          )
+        })
+      }).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` cannot be called with an empty action type]`,
+      )
+    })
+  })
+
+  describe('builder "addMatcher" method', () => {
+    const prepareNumberAction = (payload: number) => ({
+      payload,
+      meta: { type: 'number_action' },
+    })
+    const prepareStringAction = (payload: string) => ({
+      payload,
+      meta: { type: 'string_action' },
+    })
+
+    const numberActionMatcher = (
+      a: UnknownAction,
+    ): a is PayloadAction<number> =>
+      isPlainObject(a.meta) &&
+      'type' in a.meta &&
+      (a.meta as Record<'type', unknown>).type === 'number_action'
+
+    const stringActionMatcher = (
+      a: UnknownAction,
+    ): a is PayloadAction<string> =>
+      isPlainObject(a.meta) &&
+      'type' in a.meta &&
+      (a.meta as Record<'type', unknown>).type === 'string_action'
+
+    const incrementBy = createAction('increment', prepareNumberAction)
+    const decrementBy = createAction('decrement', prepareNumberAction)
+    const concatWith = createAction('concat', prepareStringAction)
+
+    const initialState = { numberActions: 0, stringActions: 0 }
+
+    test('uses the reducer of matching actionMatchers', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions += 1
+          })
+          .addMatcher(stringActionMatcher, (state) => {
+            state.stringActions += 1
+          }),
+      )
+      expect(reducer(undefined, incrementBy(1))).toEqual({
+        numberActions: 1,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, decrementBy(1))).toEqual({
+        numberActions: 1,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, concatWith('foo'))).toEqual({
+        numberActions: 0,
+        stringActions: 1,
+      })
+    })
+    test('falls back to defaultCase', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder
+          .addCase(concatWith, (state) => {
+            state.stringActions += 1
+          })
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions += 1
+          })
+          .addDefaultCase((state) => {
+            state.numberActions = -1
+            state.stringActions = -1
+          }),
+      )
+      expect(reducer(undefined, { type: 'somethingElse' })).toEqual({
+        numberActions: -1,
+        stringActions: -1,
+      })
+    })
+    test('runs reducer cases followed by all matching actionMatchers', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder
+          .addCase(incrementBy, (state) => {
+            state.numberActions = state.numberActions * 10 + 1
+          })
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions = state.numberActions * 10 + 2
+          })
+          .addMatcher(stringActionMatcher, (state) => {
+            state.stringActions = state.stringActions * 10 + 1
+          })
+          .addMatcher(numberActionMatcher, (state) => {
+            state.numberActions = state.numberActions * 10 + 3
+          }),
+      )
+      expect(reducer(undefined, incrementBy(1))).toEqual({
+        numberActions: 123,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, decrementBy(1))).toEqual({
+        numberActions: 23,
+        stringActions: 0,
+      })
+      expect(reducer(undefined, concatWith('foo'))).toEqual({
+        numberActions: 0,
+        stringActions: 1,
+      })
+    })
+    test('works with `actionCreator.match`', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder.addMatcher(incrementBy.match, (state) => {
+          state.numberActions += 100
+        }),
+      )
+      expect(reducer(undefined, incrementBy(1))).toEqual({
+        numberActions: 100,
+        stringActions: 0,
+      })
+    })
+    test('calling addCase, addMatcher and addDefaultCase in a nonsensical order should result in an error in development mode', () => {
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder
+            .addMatcher(numberActionMatcher, () => {})
+            .addCase(incrementBy, () => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` should only be called before calling \`builder.addMatcher\`]`,
+      )
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder.addDefaultCase(() => {}).addCase(incrementBy, () => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addCase\` should only be called before calling \`builder.addDefaultCase\`]`,
+      )
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder
+            .addDefaultCase(() => {})
+            .addMatcher(numberActionMatcher, () => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addMatcher\` should only be called before calling \`builder.addDefaultCase\`]`,
+      )
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder.addDefaultCase(() => {}).addDefaultCase(() => {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addDefaultCase\` can only be called once]`,
+      )
+    })
+  })
+  describe('builder "addAsyncThunk" method', () => {
+    const initialState = { todos: [] as Todo[], loading: false, errored: false }
+    test('uses the matching reducer for each action type', () => {
+      const reducer = createReducer(initialState, (builder) =>
+        builder.addAsyncThunk(addTodoThunk, {
+          pending(state) {
+            state.loading = true
+          },
+          fulfilled(state, action) {
+            state.todos.push(action.payload)
+          },
+          rejected(state) {
+            state.errored = true
+          },
+          settled(state) {
+            state.loading = false
+          },
+        }),
+      )
+      const todo: Todo = { text: 'test' }
+      expect(reducer(undefined, addTodoThunk.pending('test', todo))).toEqual({
+        todos: [],
+        loading: true,
+        errored: false,
+      })
+      expect(
+        reducer(undefined, addTodoThunk.fulfilled(todo, 'test', todo)),
+      ).toEqual({
+        todos: [todo],
+        loading: false,
+        errored: false,
+      })
+      expect(
+        reducer(undefined, addTodoThunk.rejected(new Error(), 'test', todo)),
+      ).toEqual({
+        todos: [],
+        loading: false,
+        errored: true,
+      })
+    })
+    test('calling addAsyncThunk after addDefaultCase should result in an error in development mode', () => {
+      expect(() =>
+        createReducer(initialState, (builder: any) =>
+          builder.addDefaultCase(() => {}).addAsyncThunk(addTodoThunk, {}),
+        ),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: \`builder.addAsyncThunk\` should only be called before calling \`builder.addDefaultCase\`]`,
+      )
+    })
+  })
+})
+
+function behavesLikeReducer(todosReducer: TodosReducer) {
+  it('should handle initial state', () => {
+    const initialAction = { type: '', payload: undefined }
+    expect(todosReducer(undefined, initialAction)).toEqual([])
+  })
+
+  it('should handle ADD_TODO', () => {
+    expect(
+      todosReducer([], {
+        type: 'ADD_TODO',
+        payload: { newTodo: { text: 'Run the tests' } },
+      }),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: false,
+      },
+    ])
+
+    expect(
+      todosReducer(
+        [
+          {
+            text: 'Run the tests',
+            completed: false,
+          },
+        ],
+        {
+          type: 'ADD_TODO',
+          payload: { newTodo: { text: 'Use Redux' } },
+        },
+      ),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: false,
+      },
+      {
+        text: 'Use Redux',
+        completed: false,
+      },
+    ])
+
+    expect(
+      todosReducer(
+        [
+          {
+            text: 'Run the tests',
+            completed: false,
+          },
+          {
+            text: 'Use Redux',
+            completed: false,
+          },
+        ],
+        {
+          type: 'ADD_TODO',
+          payload: { newTodo: { text: 'Fix the tests' } },
+        },
+      ),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: false,
+      },
+      {
+        text: 'Use Redux',
+        completed: false,
+      },
+      {
+        text: 'Fix the tests',
+        completed: false,
+      },
+    ])
+  })
+
+  it('should handle TOGGLE_TODO', () => {
+    expect(
+      todosReducer(
+        [
+          {
+            text: 'Run the tests',
+            completed: false,
+          },
+          {
+            text: 'Use Redux',
+            completed: false,
+          },
+        ],
+        {
+          type: 'TOGGLE_TODO',
+          payload: { index: 0 },
+        },
+      ),
+    ).toEqual([
+      {
+        text: 'Run the tests',
+        completed: true,
+      },
+      {
+        text: 'Use Redux',
+        completed: false,
+      },
+    ])
+  })
+}
Index: node_modules/@reduxjs/toolkit/src/tests/createSlice.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createSlice.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createSlice.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,995 @@
+import type {
+  Action,
+  ActionCreatorWithNonInferrablePayload,
+  ActionCreatorWithOptionalPayload,
+  ActionCreatorWithPayload,
+  ActionCreatorWithPreparedPayload,
+  ActionCreatorWithoutPayload,
+  ActionReducerMapBuilder,
+  AsyncThunk,
+  CaseReducer,
+  PayloadAction,
+  PayloadActionCreator,
+  Reducer,
+  ReducerCreators,
+  SerializedError,
+  SliceCaseReducers,
+  ThunkDispatch,
+  UnknownAction,
+  ValidateSliceCaseReducers,
+} from '@reduxjs/toolkit'
+import {
+  asyncThunkCreator,
+  buildCreateSlice,
+  configureStore,
+  createAction,
+  createAsyncThunk,
+  createSlice,
+  isRejected,
+} from '@reduxjs/toolkit'
+import { castDraft } from 'immer'
+
+describe('type tests', () => {
+  const counterSlice = createSlice({
+    name: 'counter',
+    initialState: 0,
+    reducers: {
+      increment: (state: number, action) => state + action.payload,
+      decrement: (state: number, action) => state - action.payload,
+    },
+  })
+
+  test('Slice name is strongly typed.', () => {
+    const uiSlice = createSlice({
+      name: 'ui',
+      initialState: 0,
+      reducers: {
+        goToNext: (state: number, action) => state + action.payload,
+        goToPrevious: (state: number, action) => state - action.payload,
+      },
+    })
+
+    const actionCreators = {
+      [counterSlice.name]: { ...counterSlice.actions },
+      [uiSlice.name]: { ...uiSlice.actions },
+    }
+
+    expectTypeOf(counterSlice.actions).toEqualTypeOf(actionCreators.counter)
+
+    expectTypeOf(uiSlice.actions).toEqualTypeOf(actionCreators.ui)
+
+    expectTypeOf(actionCreators).not.toHaveProperty('anyKey')
+  })
+
+  test("createSlice() infers the returned slice's type.", () => {
+    const firstAction = createAction<{ count: number }>('FIRST_ACTION')
+
+    const slice = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment: (state: number, action) => state + action.payload,
+        decrement: (state: number, action) => state - action.payload,
+      },
+      extraReducers: (builder) => {
+        builder.addCase(
+          firstAction,
+          (state, action) => state + action.payload.count,
+        )
+      },
+    })
+
+    test('Reducer', () => {
+      expectTypeOf(slice.reducer).toMatchTypeOf<
+        Reducer<number, PayloadAction>
+      >()
+
+      expectTypeOf(slice.reducer).not.toMatchTypeOf<
+        Reducer<string, PayloadAction>
+      >()
+    })
+
+    test('Actions', () => {
+      slice.actions.increment(1)
+      slice.actions.decrement(1)
+
+      expectTypeOf(slice.actions).not.toHaveProperty('other')
+    })
+  })
+
+  test('Slice action creator types are inferred.', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment: (state) => state + 1,
+        decrement: (
+          state,
+          { payload = 1 }: PayloadAction<number | undefined>,
+        ) => state - payload,
+        multiply: (state, { payload }: PayloadAction<number | number[]>) =>
+          Array.isArray(payload)
+            ? payload.reduce((acc, val) => acc * val, state)
+            : state * payload,
+        addTwo: {
+          reducer: (s, { payload }: PayloadAction<number>) => s + payload,
+          prepare: (a: number, b: number) => ({
+            payload: a + b,
+          }),
+        },
+      },
+    })
+
+    expectTypeOf(
+      counter.actions.increment,
+    ).toMatchTypeOf<ActionCreatorWithoutPayload>()
+
+    counter.actions.increment()
+
+    expectTypeOf(counter.actions.decrement).toMatchTypeOf<
+      ActionCreatorWithOptionalPayload<number | undefined>
+    >()
+
+    counter.actions.decrement()
+    counter.actions.decrement(2)
+
+    expectTypeOf(counter.actions.multiply).toMatchTypeOf<
+      ActionCreatorWithPayload<number | number[]>
+    >()
+
+    counter.actions.multiply(2)
+    counter.actions.multiply([2, 3, 4])
+
+    expectTypeOf(counter.actions.addTwo).toMatchTypeOf<
+      ActionCreatorWithPreparedPayload<[number, number], number>
+    >()
+
+    counter.actions.addTwo(1, 2)
+
+    expectTypeOf(counter.actions.multiply).parameters.not.toMatchTypeOf<[]>()
+
+    expectTypeOf(counter.actions.multiply).parameter(0).not.toBeString()
+
+    expectTypeOf(counter.actions.addTwo).parameters.not.toMatchTypeOf<
+      [number]
+    >()
+
+    expectTypeOf(counter.actions.addTwo).parameters.toEqualTypeOf<
+      [number, number]
+    >()
+  })
+
+  test('Slice action creator types properties are strongly typed', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment: (state) => state + 1,
+        decrement: (state) => state - 1,
+        multiply: (state, { payload }: PayloadAction<number | number[]>) =>
+          Array.isArray(payload)
+            ? payload.reduce((acc, val) => acc * val, state)
+            : state * payload,
+      },
+    })
+
+    expectTypeOf(
+      counter.actions.increment.type,
+    ).toEqualTypeOf<'counter/increment'>()
+
+    expectTypeOf(
+      counter.actions.increment().type,
+    ).toEqualTypeOf<'counter/increment'>()
+
+    expectTypeOf(
+      counter.actions.decrement.type,
+    ).toEqualTypeOf<'counter/decrement'>()
+
+    expectTypeOf(
+      counter.actions.decrement().type,
+    ).toEqualTypeOf<'counter/decrement'>()
+
+    expectTypeOf(
+      counter.actions.multiply.type,
+    ).toEqualTypeOf<'counter/multiply'>()
+
+    expectTypeOf(
+      counter.actions.multiply(1).type,
+    ).toEqualTypeOf<'counter/multiply'>()
+
+    expectTypeOf(
+      counter.actions.increment.type,
+    ).not.toMatchTypeOf<'increment'>()
+  })
+
+  test('Slice action creator types are inferred for enhanced reducers.', () => {
+    const counter = createSlice({
+      name: 'test',
+      initialState: { counter: 0, concat: '' },
+      reducers: {
+        incrementByStrLen: {
+          reducer: (state, action: PayloadAction<number>) => {
+            state.counter += action.payload
+          },
+          prepare: (payload: string) => ({
+            payload: payload.length,
+          }),
+        },
+        concatMetaStrLen: {
+          reducer: (state, action: PayloadAction<string>) => {
+            state.concat += action.payload
+          },
+          prepare: (payload: string) => ({
+            payload,
+            meta: payload.length,
+          }),
+        },
+      },
+    })
+
+    expectTypeOf(
+      counter.actions.incrementByStrLen('test').type,
+    ).toEqualTypeOf<'test/incrementByStrLen'>()
+
+    expectTypeOf(counter.actions.incrementByStrLen('test').payload).toBeNumber()
+
+    expectTypeOf(counter.actions.concatMetaStrLen('test').payload).toBeString()
+
+    expectTypeOf(counter.actions.concatMetaStrLen('test').meta).toBeNumber()
+
+    expectTypeOf(
+      counter.actions.incrementByStrLen('test').payload,
+    ).not.toBeString()
+
+    expectTypeOf(counter.actions.concatMetaStrLen('test').meta).not.toBeString()
+  })
+
+  test('access meta and error from reducer', () => {
+    const counter = createSlice({
+      name: 'test',
+      initialState: { counter: 0, concat: '' },
+      reducers: {
+        // case: meta and error not used in reducer
+        testDefaultMetaAndError: {
+          reducer(_, action: PayloadAction<number, string>) {},
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 'error' as 'error',
+          }),
+        },
+        // case: meta and error marked as "unknown" in reducer
+        testUnknownMetaAndError: {
+          reducer(
+            _,
+            action: PayloadAction<number, string, unknown, unknown>,
+          ) {},
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 'error' as 'error',
+          }),
+        },
+        // case: meta and error are typed in the reducer as returned by prepare
+        testMetaAndError: {
+          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 'error' as 'error',
+          }),
+        },
+        // case: meta is typed differently in the reducer than returned from prepare
+        testErroneousMeta: {
+          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},
+          // @ts-expect-error
+          prepare: (payload: number) => ({
+            payload,
+            meta: 1,
+            error: 'error' as 'error',
+          }),
+        },
+        // case: error is typed differently in the reducer than returned from prepare
+        testErroneousError: {
+          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},
+          // @ts-expect-error
+          prepare: (payload: number) => ({
+            payload,
+            meta: 'meta' as 'meta',
+            error: 1,
+          }),
+        },
+      },
+    })
+  })
+
+  test('returned case reducer has the correct type', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: 0,
+      reducers: {
+        increment(state, action: PayloadAction<number>) {
+          return state + action.payload
+        },
+        decrement: {
+          reducer(state, action: PayloadAction<number>) {
+            return state - action.payload
+          },
+          prepare(amount: number) {
+            return { payload: amount }
+          },
+        },
+      },
+    })
+
+    test('Should match positively', () => {
+      expectTypeOf(counter.caseReducers.increment).toMatchTypeOf<
+        (state: number, action: PayloadAction<number>) => number | void
+      >()
+    })
+
+    test('Should match positively for reducers with prepare callback', () => {
+      expectTypeOf(counter.caseReducers.decrement).toMatchTypeOf<
+        (state: number, action: PayloadAction<number>) => number | void
+      >()
+    })
+
+    test("Should not mismatch the payload if it's a simple reducer", () => {
+      expectTypeOf(counter.caseReducers.increment).not.toMatchTypeOf<
+        (state: number, action: PayloadAction<string>) => number | void
+      >()
+    })
+
+    test("Should not mismatch the payload if it's a reducer with a prepare callback", () => {
+      expectTypeOf(counter.caseReducers.decrement).not.toMatchTypeOf<
+        (state: number, action: PayloadAction<string>) => number | void
+      >()
+    })
+
+    test("Should not include entries that don't exist", () => {
+      expectTypeOf(counter.caseReducers).not.toHaveProperty(
+        'someThingNonExistent',
+      )
+    })
+  })
+
+  test('prepared payload does not match action payload - should cause an error.', () => {
+    const counter = createSlice({
+      name: 'counter',
+      initialState: { counter: 0 },
+      reducers: {
+        increment: {
+          reducer(state, action: PayloadAction<string>) {
+            state.counter += action.payload.length
+          },
+          // @ts-expect-error
+          prepare(x: string) {
+            return {
+              payload: 6,
+            }
+          },
+        },
+      },
+    })
+  })
+
+  test('if no Payload Type is specified, accept any payload', () => {
+    // see https://github.com/reduxjs/redux-toolkit/issues/165
+
+    const initialState = {
+      name: null,
+    }
+
+    const mySlice = createSlice({
+      name: 'name',
+      initialState,
+      reducers: {
+        setName: (state, action) => {
+          state.name = action.payload
+        },
+      },
+    })
+
+    expectTypeOf(
+      mySlice.actions.setName,
+    ).toMatchTypeOf<ActionCreatorWithNonInferrablePayload>()
+
+    const x = mySlice.actions.setName
+
+    mySlice.actions.setName(null)
+    mySlice.actions.setName('asd')
+    mySlice.actions.setName(5)
+  })
+
+  test('actions.x.match()', () => {
+    const mySlice = createSlice({
+      name: 'name',
+      initialState: { name: 'test' },
+      reducers: {
+        setName: (state, action: PayloadAction<string>) => {
+          state.name = action.payload
+        },
+      },
+    })
+
+    const x: Action<string> = {} as any
+    if (mySlice.actions.setName.match(x)) {
+      expectTypeOf(x.type).toEqualTypeOf<'name/setName'>()
+
+      expectTypeOf(x.payload).toBeString()
+    } else {
+      expectTypeOf(x.type).not.toMatchTypeOf<'name/setName'>()
+
+      expectTypeOf(x).not.toHaveProperty('payload')
+    }
+  })
+
+  test('builder callback for extraReducers', () => {
+    createSlice({
+      name: 'test',
+      initialState: 0,
+      reducers: {},
+      extraReducers: (builder) => {
+        expectTypeOf(builder).toEqualTypeOf<ActionReducerMapBuilder<number>>()
+      },
+    })
+  })
+
+  test('wrapping createSlice should be possible', () => {
+    interface GenericState<T> {
+      data?: T
+      status: 'loading' | 'finished' | 'error'
+    }
+
+    const createGenericSlice = <
+      T,
+      Reducers extends SliceCaseReducers<GenericState<T>>,
+    >({
+      name = '',
+      initialState,
+      reducers,
+    }: {
+      name: string
+      initialState: GenericState<T>
+      reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>
+    }) => {
+      return createSlice({
+        name,
+        initialState,
+        reducers: {
+          start(state) {
+            state.status = 'loading'
+          },
+          success(state: GenericState<T>, action: PayloadAction<T>) {
+            state.data = action.payload
+            state.status = 'finished'
+          },
+          ...reducers,
+        },
+      })
+    }
+
+    const wrappedSlice = createGenericSlice({
+      name: 'test',
+      initialState: { status: 'loading' } as GenericState<string>,
+      reducers: {
+        magic(state) {
+          expectTypeOf(state).toEqualTypeOf<GenericState<string>>()
+
+          expectTypeOf(state).not.toMatchTypeOf<GenericState<number>>()
+
+          state.status = 'finished'
+          state.data = 'hocus pocus'
+        },
+      },
+    })
+
+    expectTypeOf(wrappedSlice.actions.success).toMatchTypeOf<
+      ActionCreatorWithPayload<string>
+    >()
+
+    expectTypeOf(wrappedSlice.actions.magic).toMatchTypeOf<
+      ActionCreatorWithoutPayload<string>
+    >()
+  })
+
+  test('extraReducers', () => {
+    interface GenericState<T> {
+      data: T | null
+    }
+
+    function createDataSlice<
+      T,
+      Reducers extends SliceCaseReducers<GenericState<T>>,
+    >(
+      name: string,
+      reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>,
+      initialState: GenericState<T>,
+    ) {
+      const doNothing = createAction<undefined>('doNothing')
+      const setData = createAction<T>('setData')
+
+      const slice = createSlice({
+        name,
+        initialState,
+        reducers,
+        extraReducers: (builder) => {
+          builder.addCase(doNothing, (state) => {
+            return { ...state }
+          })
+          builder.addCase(setData, (state, { payload }) => {
+            return {
+              ...state,
+              data: payload,
+            }
+          })
+        },
+      })
+      return { doNothing, setData, slice }
+    }
+  })
+
+  test('slice selectors', () => {
+    const sliceWithoutSelectors = createSlice({
+      name: '',
+      initialState: '',
+      reducers: {},
+    })
+
+    expectTypeOf(sliceWithoutSelectors.selectors).not.toHaveProperty('foo')
+
+    const sliceWithSelectors = createSlice({
+      name: 'counter',
+      initialState: { value: 0 },
+      reducers: {
+        increment: (state) => {
+          state.value += 1
+        },
+      },
+      selectors: {
+        selectValue: (state) => state.value,
+        selectMultiply: (state, multiplier: number) => state.value * multiplier,
+        selectToFixed: Object.assign(
+          (state: { value: number }) => state.value.toFixed(2),
+          { static: true },
+        ),
+      },
+    })
+
+    const rootState = {
+      [sliceWithSelectors.reducerPath]: sliceWithSelectors.getInitialState(),
+    }
+
+    const { selectValue, selectMultiply, selectToFixed } =
+      sliceWithSelectors.selectors
+
+    expectTypeOf(selectValue(rootState)).toBeNumber()
+
+    expectTypeOf(selectMultiply(rootState, 2)).toBeNumber()
+
+    expectTypeOf(selectToFixed(rootState)).toBeString()
+
+    expectTypeOf(selectToFixed.unwrapped.static).toBeBoolean()
+
+    const nestedState = {
+      nested: rootState,
+    }
+
+    const nestedSelectors = sliceWithSelectors.getSelectors(
+      (rootState: typeof nestedState) => rootState.nested.counter,
+    )
+
+    expectTypeOf(nestedSelectors.selectValue(nestedState)).toBeNumber()
+
+    expectTypeOf(nestedSelectors.selectMultiply(nestedState, 2)).toBeNumber()
+
+    expectTypeOf(nestedSelectors.selectToFixed(nestedState)).toBeString()
+  })
+
+  test('reducer callback', () => {
+    interface TestState {
+      foo: string
+    }
+
+    interface TestArg {
+      test: string
+    }
+
+    interface TestReturned {
+      payload: string
+    }
+
+    interface TestReject {
+      cause: string
+    }
+
+    const slice = createSlice({
+      name: 'test',
+      initialState: {} as TestState,
+      reducers: (create) => {
+        const preTypedAsyncThunk = create.asyncThunk.withTypes<{
+          rejectValue: TestReject
+        }>()
+
+        // @ts-expect-error
+        create.asyncThunk<any, any, { state: StoreState }>(() => {})
+
+        // @ts-expect-error
+        create.asyncThunk.withTypes<{
+          rejectValue: string
+          dispatch: StoreDispatch
+        }>()
+
+        return {
+          normalReducer: create.reducer<string>((state, action) => {
+            expectTypeOf(state).toEqualTypeOf<TestState>()
+
+            expectTypeOf(action.payload).toBeString()
+          }),
+          optionalReducer: create.reducer<string | undefined>(
+            (state, action) => {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()
+            },
+          ),
+          noActionReducer: create.reducer((state) => {
+            expectTypeOf(state).toEqualTypeOf<TestState>()
+          }),
+          preparedReducer: create.preparedReducer(
+            (payload: string) => ({
+              payload,
+              meta: 'meta' as const,
+              error: 'error' as const,
+            }),
+            (state, action) => {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.payload).toBeString()
+
+              expectTypeOf(action.meta).toEqualTypeOf<'meta'>()
+
+              expectTypeOf(action.error).toEqualTypeOf<'error'>()
+            },
+          ),
+          testInferVoid: create.asyncThunk(() => {}, {
+            pending(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+            },
+            fulfilled(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+
+              expectTypeOf(action.payload).toBeVoid()
+            },
+            rejected(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+
+              expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+            },
+            settled(state, action) {
+              expectTypeOf(state).toEqualTypeOf<TestState>()
+
+              expectTypeOf(action.meta.arg).toBeVoid()
+
+              if (isRejected(action)) {
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+              } else {
+                expectTypeOf(action.payload).toBeVoid()
+              }
+            },
+          }),
+          testInfer: create.asyncThunk(
+            function payloadCreator(arg: TestArg, api) {
+              return Promise.resolve<TestReturned>({ payload: 'foo' })
+            },
+            {
+              pending(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+              },
+              fulfilled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+              },
+              rejected(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+              },
+              settled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                if (isRejected(action)) {
+                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+                } else {
+                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+                }
+              },
+            },
+          ),
+          testExplicitType: create.asyncThunk<
+            TestReturned,
+            TestArg,
+            {
+              rejectValue: TestReject
+            }
+          >(
+            function payloadCreator(arg, api) {
+              // here would be a circular reference
+              expectTypeOf(api.getState()).toBeUnknown()
+              // here would be a circular reference
+              expectTypeOf(api.dispatch).toMatchTypeOf<
+                ThunkDispatch<any, any, any>
+              >()
+
+              // so you need to cast inside instead
+              const getState = api.getState as () => StoreState
+              const dispatch = api.dispatch as StoreDispatch
+
+              expectTypeOf(arg).toEqualTypeOf<TestArg>()
+
+              expectTypeOf(api.rejectWithValue).toMatchTypeOf<
+                (value: TestReject) => any
+              >()
+
+              return Promise.resolve({ payload: 'foo' })
+            },
+            {
+              pending(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+              },
+              fulfilled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+              },
+              rejected(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<
+                  TestReject | undefined
+                >()
+              },
+              settled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                if (isRejected(action)) {
+                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                  expectTypeOf(action.payload).toEqualTypeOf<
+                    TestReject | undefined
+                  >()
+                } else {
+                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+                }
+              },
+            },
+          ),
+          testPreTyped: preTypedAsyncThunk(
+            function payloadCreator(arg: TestArg, api) {
+              expectTypeOf(api.rejectWithValue).toMatchTypeOf<
+                (value: TestReject) => any
+              >()
+
+              return Promise.resolve<TestReturned>({ payload: 'foo' })
+            },
+            {
+              pending(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+              },
+              fulfilled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+              },
+              rejected(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                expectTypeOf(action.payload).toEqualTypeOf<
+                  TestReject | undefined
+                >()
+              },
+              settled(state, action) {
+                expectTypeOf(state).toEqualTypeOf<TestState>()
+
+                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()
+
+                if (isRejected(action)) {
+                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+                  expectTypeOf(action.payload).toEqualTypeOf<
+                    TestReject | undefined
+                  >()
+                } else {
+                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()
+                }
+              },
+            },
+          ),
+        }
+      },
+    })
+
+    const store = configureStore({ reducer: { test: slice.reducer } })
+
+    type StoreState = ReturnType<typeof store.getState>
+
+    type StoreDispatch = typeof store.dispatch
+
+    expectTypeOf(slice.actions.normalReducer).toMatchTypeOf<
+      PayloadActionCreator<string>
+    >()
+
+    expectTypeOf(slice.actions.normalReducer).toBeCallableWith('')
+
+    expectTypeOf(slice.actions.normalReducer).parameters.not.toMatchTypeOf<[]>()
+
+    expectTypeOf(slice.actions.normalReducer).parameters.not.toMatchTypeOf<
+      [number]
+    >()
+
+    expectTypeOf(slice.actions.optionalReducer).toMatchTypeOf<
+      ActionCreatorWithOptionalPayload<string | undefined>
+    >()
+
+    expectTypeOf(slice.actions.optionalReducer).toBeCallableWith()
+
+    expectTypeOf(slice.actions.optionalReducer).toBeCallableWith('')
+
+    expectTypeOf(slice.actions.optionalReducer).parameter(0).not.toBeNumber()
+
+    expectTypeOf(
+      slice.actions.noActionReducer,
+    ).toMatchTypeOf<ActionCreatorWithoutPayload>()
+
+    expectTypeOf(slice.actions.noActionReducer).toBeCallableWith()
+
+    expectTypeOf(slice.actions.noActionReducer).parameter(0).not.toBeString()
+
+    expectTypeOf(slice.actions.preparedReducer).toEqualTypeOf<
+      ActionCreatorWithPreparedPayload<
+        [string],
+        string,
+        'test/preparedReducer',
+        'error',
+        'meta'
+      >
+    >()
+
+    expectTypeOf(slice.actions.testInferVoid).toEqualTypeOf<
+      AsyncThunk<void, void, {}>
+    >()
+
+    expectTypeOf(slice.actions.testInferVoid).toBeCallableWith()
+
+    expectTypeOf(slice.actions.testInfer).toEqualTypeOf<
+      AsyncThunk<TestReturned, TestArg, {}>
+    >()
+
+    expectTypeOf(slice.actions.testExplicitType).toEqualTypeOf<
+      AsyncThunk<TestReturned, TestArg, { rejectValue: TestReject }>
+    >()
+
+    type TestInferThunk = AsyncThunk<TestReturned, TestArg, {}>
+
+    expectTypeOf(slice.caseReducers.testInfer.pending).toEqualTypeOf<
+      CaseReducer<TestState, ReturnType<TestInferThunk['pending']>>
+    >()
+
+    expectTypeOf(slice.caseReducers.testInfer.fulfilled).toEqualTypeOf<
+      CaseReducer<TestState, ReturnType<TestInferThunk['fulfilled']>>
+    >()
+
+    expectTypeOf(slice.caseReducers.testInfer.rejected).toEqualTypeOf<
+      CaseReducer<TestState, ReturnType<TestInferThunk['rejected']>>
+    >()
+  })
+
+  test('wrapping createSlice should be possible, with callback', () => {
+    interface GenericState<T> {
+      data?: T
+      status: 'loading' | 'finished' | 'error'
+    }
+
+    const createGenericSlice = <
+      T,
+      Reducers extends SliceCaseReducers<GenericState<T>>,
+    >({
+      name = '',
+      initialState,
+      reducers,
+    }: {
+      name: string
+      initialState: GenericState<T>
+      reducers: (create: ReducerCreators<GenericState<T>>) => Reducers
+    }) => {
+      return createSlice({
+        name,
+        initialState,
+        reducers: (create) => ({
+          start: create.reducer((state) => {
+            state.status = 'loading'
+          }),
+          success: create.reducer<T>((state, action) => {
+            state.data = castDraft(action.payload)
+            state.status = 'finished'
+          }),
+          ...reducers(create),
+        }),
+      })
+    }
+
+    const wrappedSlice = createGenericSlice({
+      name: 'test',
+      initialState: { status: 'loading' } as GenericState<string>,
+      reducers: (create) => ({
+        magic: create.reducer((state) => {
+          expectTypeOf(state).toEqualTypeOf<GenericState<string>>()
+
+          expectTypeOf(state).not.toMatchTypeOf<GenericState<number>>()
+
+          state.status = 'finished'
+          state.data = 'hocus pocus'
+        }),
+      }),
+    })
+
+    expectTypeOf(wrappedSlice.actions.success).toMatchTypeOf<
+      ActionCreatorWithPayload<string>
+    >()
+
+    expectTypeOf(wrappedSlice.actions.magic).toMatchTypeOf<
+      ActionCreatorWithoutPayload<string>
+    >()
+  })
+
+  test('selectSlice', () => {
+    expectTypeOf(counterSlice.selectSlice({ counter: 0 })).toBeNumber()
+
+    // We use `not.toEqualTypeOf` instead of `not.toMatchTypeOf`
+    // because `toMatchTypeOf` allows missing properties
+    expectTypeOf(counterSlice.selectSlice).parameter(0).not.toEqualTypeOf<{}>()
+  })
+
+  test('buildCreateSlice', () => {
+    expectTypeOf(buildCreateSlice()).toEqualTypeOf(createSlice)
+
+    buildCreateSlice({
+      // @ts-expect-error not possible to recreate shape because symbol is not exported
+      creators: { asyncThunk: { [Symbol()]: createAsyncThunk } },
+    })
+    buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/createSlice.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/createSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/createSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,987 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { PayloadAction, WithSlice } from '@reduxjs/toolkit'
+import {
+  asyncThunkCreator,
+  buildCreateSlice,
+  combineSlices,
+  configureStore,
+  createAction,
+  createAsyncThunk,
+  createSlice,
+} from '@reduxjs/toolkit'
+
+type CreateSlice = typeof createSlice
+
+describe('createSlice', () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  beforeEach(() => {
+    vi.clearAllMocks()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+  })
+
+  describe('when slice is undefined', () => {
+    it('should throw an error', () => {
+      expect(() =>
+        // @ts-ignore
+        createSlice({
+          reducers: {
+            increment: (state) => state + 1,
+            multiply: (state, action: PayloadAction<number>) =>
+              state * action.payload,
+          },
+          initialState: 0,
+        }),
+      ).toThrowError()
+    })
+  })
+
+  describe('when slice is an empty string', () => {
+    it('should throw an error', () => {
+      expect(() =>
+        createSlice({
+          name: '',
+          reducers: {
+            increment: (state) => state + 1,
+            multiply: (state, action: PayloadAction<number>) =>
+              state * action.payload,
+          },
+          initialState: 0,
+        }),
+      ).toThrowError()
+    })
+  })
+
+  describe('when initial state is undefined', () => {
+    beforeEach(() => {
+      vi.stubEnv('NODE_ENV', 'development')
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    it('should throw an error', () => {
+      createSlice({
+        name: 'test',
+        reducers: {},
+        initialState: undefined,
+      })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',
+      )
+    })
+  })
+
+  describe('when passing slice', () => {
+    const { actions, reducer, caseReducers } = createSlice({
+      reducers: {
+        increment: (state) => state + 1,
+      },
+      initialState: 0,
+      name: 'cool',
+    })
+
+    it('should create increment action', () => {
+      expect(actions.hasOwnProperty('increment')).toBe(true)
+    })
+
+    it('should have the correct action for increment', () => {
+      expect(actions.increment()).toEqual({
+        type: 'cool/increment',
+        payload: undefined,
+      })
+    })
+
+    it('should return the correct value from reducer', () => {
+      expect(reducer(undefined, actions.increment())).toEqual(1)
+    })
+
+    it('should include the generated case reducers', () => {
+      expect(caseReducers).toBeTruthy()
+      expect(caseReducers.increment).toBeTruthy()
+      expect(typeof caseReducers.increment).toBe('function')
+    })
+
+    it('getInitialState should return the state', () => {
+      const initialState = 42
+      const slice = createSlice({
+        name: 'counter',
+        initialState,
+        reducers: {},
+      })
+
+      expect(slice.getInitialState()).toBe(initialState)
+    })
+
+    it('should allow non-draftable initial state', () => {
+      expect(() =>
+        createSlice({
+          name: 'params',
+          initialState: new URLSearchParams(),
+          reducers: {},
+        }),
+      ).not.toThrowError()
+    })
+  })
+
+  describe('when initialState is a function', () => {
+    const initialState = () => ({ user: '' })
+
+    const { actions, reducer } = createSlice({
+      reducers: {
+        setUserName: (state, action) => {
+          state.user = action.payload
+        },
+      },
+      initialState,
+      name: 'user',
+    })
+
+    it('should set the username', () => {
+      expect(reducer(undefined, actions.setUserName('eric'))).toEqual({
+        user: 'eric',
+      })
+    })
+
+    it('getInitialState should return the state', () => {
+      const initialState = () => 42
+      const slice = createSlice({
+        name: 'counter',
+        initialState,
+        reducers: {},
+      })
+
+      expect(slice.getInitialState()).toBe(42)
+    })
+
+    it('should allow non-draftable initial state', () => {
+      expect(() =>
+        createSlice({
+          name: 'params',
+          initialState: () => new URLSearchParams(),
+          reducers: {},
+        }),
+      ).not.toThrowError()
+    })
+  })
+
+  describe('when mutating state object', () => {
+    const initialState = { user: '' }
+
+    const { actions, reducer } = createSlice({
+      reducers: {
+        setUserName: (state, action) => {
+          state.user = action.payload
+        },
+      },
+      initialState,
+      name: 'user',
+    })
+
+    it('should set the username', () => {
+      expect(reducer(initialState, actions.setUserName('eric'))).toEqual({
+        user: 'eric',
+      })
+    })
+  })
+
+  describe('when passing extra reducers', () => {
+    const addMore = createAction<{ amount: number }>('ADD_MORE')
+
+    const { reducer } = createSlice({
+      name: 'test',
+      reducers: {
+        increment: (state) => state + 1,
+        multiply: (state, action) => state * action.payload,
+      },
+      extraReducers: (builder) => {
+        builder.addCase(
+          addMore,
+          (state, action) => state + action.payload.amount,
+        )
+      },
+
+      initialState: 0,
+    })
+
+    it('should call extra reducers when their actions are dispatched', () => {
+      const result = reducer(10, addMore({ amount: 5 }))
+
+      expect(result).toBe(15)
+    })
+
+    describe('builder callback for extraReducers', () => {
+      const increment = createAction<number, 'increment'>('increment')
+
+      test('can be used with actionCreators', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addCase(
+              increment,
+              (state, action) => state + action.payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      test('can be used with string action types', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addCase(
+              'increment',
+              (state, action: { type: 'increment'; payload: number }) =>
+                state + action.payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      test('prevents the same action type from being specified twice', () => {
+        expect(() => {
+          const slice = createSlice({
+            name: 'counter',
+            initialState: 0,
+            reducers: {},
+            extraReducers: (builder) =>
+              builder
+                .addCase('increment', (state) => state + 1)
+                .addCase('increment', (state) => state + 1),
+          })
+          slice.reducer(undefined, { type: 'unrelated' })
+        }).toThrowErrorMatchingInlineSnapshot(
+          `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
+        )
+      })
+
+      test('can be used with addAsyncThunk and async thunks', () => {
+        const asyncThunk = createAsyncThunk('test', (n: number) => n)
+        const slice = createSlice({
+          name: 'counter',
+          initialState: {
+            loading: false,
+            errored: false,
+            value: 0,
+          },
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addAsyncThunk(asyncThunk, {
+              pending(state) {
+                state.loading = true
+              },
+              fulfilled(state, action) {
+                state.value = action.payload
+              },
+              rejected(state) {
+                state.errored = true
+              },
+              settled(state) {
+                state.loading = false
+              },
+            }),
+        })
+        expect(
+          slice.reducer(undefined, asyncThunk.pending('requestId', 5)),
+        ).toEqual({
+          loading: true,
+          errored: false,
+          value: 0,
+        })
+        expect(
+          slice.reducer(undefined, asyncThunk.fulfilled(5, 'requestId', 5)),
+        ).toEqual({
+          loading: false,
+          errored: false,
+          value: 5,
+        })
+        expect(
+          slice.reducer(
+            undefined,
+            asyncThunk.rejected(new Error(), 'requestId', 5),
+          ),
+        ).toEqual({
+          loading: false,
+          errored: true,
+          value: 0,
+        })
+      })
+
+      test('can be used with addMatcher and type guard functions', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addMatcher(
+              increment.match,
+              (state, action: { type: 'increment'; payload: number }) =>
+                state + action.payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      test('can be used with addDefaultCase', () => {
+        const slice = createSlice({
+          name: 'counter',
+          initialState: 0,
+          reducers: {},
+          extraReducers: (builder) =>
+            builder.addDefaultCase(
+              (state, action) =>
+                state + (action as PayloadAction<number>).payload,
+            ),
+        })
+        expect(slice.reducer(0, increment(5))).toBe(5)
+      })
+
+      // for further tests, see the test of createReducer that goes way more into depth on this
+    })
+  })
+
+  describe('behavior with enhanced case reducers', () => {
+    it('should pass all arguments to the prepare function', () => {
+      const prepare = vi.fn((payload, somethingElse) => ({ payload }))
+
+      const testSlice = createSlice({
+        name: 'test',
+        initialState: 0,
+        reducers: {
+          testReducer: {
+            reducer: (s) => s,
+            prepare,
+          },
+        },
+      })
+
+      expect(testSlice.actions.testReducer('a', 1)).toEqual({
+        type: 'test/testReducer',
+        payload: 'a',
+      })
+      expect(prepare).toHaveBeenCalledWith('a', 1)
+    })
+
+    it('should call the reducer function', () => {
+      const reducer = vi.fn(() => 5)
+
+      const testSlice = createSlice({
+        name: 'test',
+        initialState: 0,
+        reducers: {
+          testReducer: {
+            reducer,
+            prepare: (payload: any) => ({ payload }),
+          },
+        },
+      })
+
+      testSlice.reducer(0, testSlice.actions.testReducer('testPayload'))
+      expect(reducer).toHaveBeenCalledWith(
+        0,
+        expect.objectContaining({ payload: 'testPayload' }),
+      )
+    })
+  })
+
+  describe('circularity', () => {
+    test('extraReducers can reference each other circularly', () => {
+      const first = createSlice({
+        name: 'first',
+        initialState: 'firstInitial',
+        reducers: {
+          something() {
+            return 'firstSomething'
+          },
+        },
+        extraReducers(builder) {
+          // eslint-disable-next-line @typescript-eslint/no-use-before-define
+          builder.addCase(second.actions.other, () => {
+            return 'firstOther'
+          })
+        },
+      })
+      const second = createSlice({
+        name: 'second',
+        initialState: 'secondInitial',
+        reducers: {
+          other() {
+            return 'secondOther'
+          },
+        },
+        extraReducers(builder) {
+          builder.addCase(first.actions.something, () => {
+            return 'secondSomething'
+          })
+        },
+      })
+
+      expect(first.reducer(undefined, { type: 'unrelated' })).toBe(
+        'firstInitial',
+      )
+      expect(first.reducer(undefined, first.actions.something())).toBe(
+        'firstSomething',
+      )
+      expect(first.reducer(undefined, second.actions.other())).toBe(
+        'firstOther',
+      )
+
+      expect(second.reducer(undefined, { type: 'unrelated' })).toBe(
+        'secondInitial',
+      )
+      expect(second.reducer(undefined, first.actions.something())).toBe(
+        'secondSomething',
+      )
+      expect(second.reducer(undefined, second.actions.other())).toBe(
+        'secondOther',
+      )
+    })
+  })
+
+  describe('Deprecation warnings', () => {
+    beforeEach(() => {
+      vi.resetModules()
+    })
+
+    afterEach(() => {
+      vi.unstubAllEnvs()
+    })
+
+    // NOTE: This needs to be in front of the later `createReducer` call to check the one-time warning
+    it('Throws an error if the legacy object notation is used', async () => {
+      const { createSlice } = await import('../createSlice')
+
+      let dummySlice = (createSlice as CreateSlice)({
+        name: 'dummy',
+        initialState: [],
+        reducers: {},
+        extraReducers: {
+          // @ts-ignore
+          a: () => [],
+        },
+      })
+      let reducer: any
+      // Have to trigger the lazy creation
+      const wrapper = () => {
+        reducer = dummySlice.reducer
+        reducer(undefined, { type: 'dummy' })
+      }
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createSlice.extraReducers` has been removed/,
+      )
+
+      dummySlice = (createSlice as CreateSlice)({
+        name: 'dummy',
+        initialState: [],
+        reducers: {},
+        extraReducers: {
+          // @ts-ignore
+          a: () => [],
+        },
+      })
+      expect(wrapper).toThrowError(
+        /The object notation for `createSlice.extraReducers` has been removed/,
+      )
+    })
+
+    // TODO Determine final production behavior here
+    it.todo('Crashes in production', () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { createSlice } = require('../createSlice')
+
+      const dummySlice = (createSlice as CreateSlice)({
+        name: 'dummy',
+        initialState: [],
+        reducers: {},
+        // @ts-ignore
+        extraReducers: {},
+      })
+      const wrapper = () => {
+        const { reducer } = dummySlice
+        reducer(undefined, { type: 'dummy' })
+      }
+
+      expect(wrapper).toThrowError(
+        /The object notation for `createSlice.extraReducers` has been removed/,
+      )
+
+      vi.unstubAllEnvs()
+    })
+  })
+  describe('slice selectors', () => {
+    const slice = createSlice({
+      name: 'counter',
+      initialState: 42,
+      reducers: {},
+      selectors: {
+        selectSlice: (state) => state,
+        selectMultiple: Object.assign(
+          (state: number, multiplier: number) => state * multiplier,
+          { test: 0 },
+        ),
+      },
+    })
+    it('expects reducer under slice.reducerPath if no selectState callback passed', () => {
+      const testState = {
+        [slice.reducerPath]: slice.getInitialState(),
+      }
+      const { selectSlice, selectMultiple } = slice.selectors
+      expect(selectSlice(testState)).toBe(slice.getInitialState())
+      expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)
+    })
+    it('allows passing a selector for a custom location', () => {
+      const customState = {
+        number: slice.getInitialState(),
+      }
+      const { selectSlice, selectMultiple } = slice.getSelectors(
+        (state: typeof customState) => state.number,
+      )
+      expect(selectSlice(customState)).toBe(slice.getInitialState())
+      expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)
+    })
+    it('allows accessing properties on the selector', () => {
+      expect(slice.selectors.selectMultiple.unwrapped.test).toBe(0)
+    })
+    it('has selectSlice attached to slice, which can go without this', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: 42,
+        reducers: {},
+      })
+      const { selectSlice } = slice
+      expect(() => selectSlice({ counter: 42 })).not.toThrow()
+      expect(selectSlice({ counter: 42 })).toBe(42)
+    })
+  })
+  describe('slice injections', () => {
+    it('uses injectInto to inject slice into combined reducer', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: 42,
+        reducers: {
+          increment: (state) => ++state,
+        },
+        selectors: {
+          selectMultiple: (state, multiplier: number) => state * multiplier,
+        },
+      })
+
+      const { increment } = slice.actions
+
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice>>()
+
+      const uninjectedState = combinedReducer(undefined, increment())
+
+      expect(uninjectedState.counter).toBe(undefined)
+
+      const injectedSlice = slice.injectInto(combinedReducer)
+
+      // selector returns initial state if undefined in real state
+      expect(injectedSlice.selectSlice(uninjectedState)).toBe(
+        slice.getInitialState(),
+      )
+      expect(injectedSlice.selectors.selectMultiple({}, 1)).toBe(
+        slice.getInitialState(),
+      )
+      expect(injectedSlice.getSelectors().selectMultiple(undefined, 1)).toBe(
+        slice.getInitialState(),
+      )
+
+      const injectedState = combinedReducer(undefined, increment())
+
+      expect(injectedSlice.selectSlice(injectedState)).toBe(
+        slice.getInitialState() + 1,
+      )
+      expect(injectedSlice.selectors.selectMultiple(injectedState, 1)).toBe(
+        slice.getInitialState() + 1,
+      )
+    })
+    it('allows providing a custom name to inject under', () => {
+      const slice = createSlice({
+        name: 'counter',
+        reducerPath: 'injected',
+        initialState: 42,
+        reducers: {
+          increment: (state) => ++state,
+        },
+        selectors: {
+          selectMultiple: (state, multiplier: number) => state * multiplier,
+        },
+      })
+
+      const { increment } = slice.actions
+
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice> & { injected2: number }>()
+
+      const uninjectedState = combinedReducer(undefined, increment())
+
+      expect(uninjectedState.injected).toBe(undefined)
+
+      const injected = slice.injectInto(combinedReducer)
+
+      const injectedState = combinedReducer(undefined, increment())
+
+      expect(injected.selectSlice(injectedState)).toBe(
+        slice.getInitialState() + 1,
+      )
+      expect(injected.selectors.selectMultiple(injectedState, 2)).toBe(
+        (slice.getInitialState() + 1) * 2,
+      )
+
+      const injected2 = slice.injectInto(combinedReducer, {
+        reducerPath: 'injected2',
+      })
+
+      const injected2State = combinedReducer(undefined, increment())
+
+      expect(injected2.selectSlice(injected2State)).toBe(
+        slice.getInitialState() + 1,
+      )
+      expect(injected2.selectors.selectMultiple(injected2State, 2)).toBe(
+        (slice.getInitialState() + 1) * 2,
+      )
+    })
+    it('avoids incorrectly caching selectors', () => {
+      const slice = createSlice({
+        name: 'counter',
+        reducerPath: 'injected',
+        initialState: 42,
+        reducers: {
+          increment: (state) => ++state,
+        },
+        selectors: {
+          selectMultiple: (state, multiplier: number) => state * multiplier,
+        },
+      })
+      expect(slice.getSelectors()).toBe(slice.getSelectors())
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice>>()
+
+      const injected = slice.injectInto(combinedReducer)
+
+      expect(injected.getSelectors()).not.toBe(slice.getSelectors())
+
+      expect(injected.getSelectors().selectMultiple(undefined, 1)).toBe(42)
+
+      expect(() =>
+        // @ts-expect-error
+        slice.getSelectors().selectMultiple(undefined, 1),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: selectState returned undefined for an uninjected slice reducer]`,
+      )
+
+      const injected2 = slice.injectInto(combinedReducer, {
+        reducerPath: 'other',
+      })
+
+      // can use same cache for localised selectors
+      expect(injected.getSelectors()).toBe(injected2.getSelectors())
+      // these should be different
+      expect(injected.selectors).not.toBe(injected2.selectors)
+    })
+    it('caches initial states for selectors', () => {
+      const slice = createSlice({
+        name: 'counter',
+        initialState: () => ({ value: 0 }),
+        reducers: {},
+        selectors: {
+          selectObj: (state) => state,
+        },
+      })
+      // not cached
+      expect(slice.getInitialState()).not.toBe(slice.getInitialState())
+      expect(slice.reducer(undefined, { type: 'dummy' })).not.toBe(
+        slice.reducer(undefined, { type: 'dummy' }),
+      )
+
+      const combinedReducer = combineSlices({
+        static: slice.reducer,
+      }).withLazyLoadedSlices<WithSlice<typeof slice>>()
+
+      const injected = slice.injectInto(combinedReducer)
+
+      // still not cached
+      expect(injected.getInitialState()).not.toBe(injected.getInitialState())
+      expect(injected.reducer(undefined, { type: 'dummy' })).not.toBe(
+        injected.reducer(undefined, { type: 'dummy' }),
+      )
+      // cached
+      expect(injected.selectSlice({})).toBe(injected.selectSlice({}))
+      expect(injected.selectors.selectObj({})).toBe(
+        injected.selectors.selectObj({}),
+      )
+    })
+  })
+  describe('reducers definition with asyncThunks', () => {
+    it('is disabled by default', () => {
+      expect(() =>
+        createSlice({
+          name: 'test',
+          initialState: [] as any[],
+          reducers: (create) => ({ thunk: create.asyncThunk(() => {}) }),
+        }),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: Cannot use \`create.asyncThunk\` in the built-in \`createSlice\`. Use \`buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\` to create a customised version of \`createSlice\`.]`,
+      )
+    })
+    const createAppSlice = buildCreateSlice({
+      creators: { asyncThunk: asyncThunkCreator },
+    })
+    function pending(state: any[], action: any) {
+      state.push(['pendingReducer', action])
+    }
+    function fulfilled(state: any[], action: any) {
+      state.push(['fulfilledReducer', action])
+    }
+    function rejected(state: any[], action: any) {
+      state.push(['rejectedReducer', action])
+    }
+    function settled(state: any[], action: any) {
+      state.push(['settledReducer', action])
+    }
+
+    test('successful thunk', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            function payloadCreator(arg: string, api) {
+              return Promise.resolve('resolved payload')
+            },
+            { pending, fulfilled, rejected, settled },
+          ),
+        }),
+      })
+
+      const store = configureStore({
+        reducer: slice.reducer,
+      })
+      await store.dispatch(slice.actions.thunkReducers('test'))
+      expect(store.getState()).toMatchObject([
+        [
+          'pendingReducer',
+          {
+            type: 'test/thunkReducers/pending',
+            payload: undefined,
+          },
+        ],
+        [
+          'fulfilledReducer',
+          {
+            type: 'test/thunkReducers/fulfilled',
+            payload: 'resolved payload',
+          },
+        ],
+        [
+          'settledReducer',
+          {
+            type: 'test/thunkReducers/fulfilled',
+            payload: 'resolved payload',
+          },
+        ],
+      ])
+    })
+
+    test('rejected thunk', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            // payloadCreator isn't allowed to return never
+            function payloadCreator(arg: string, api): any {
+              throw new Error('')
+            },
+            { pending, fulfilled, rejected, settled },
+          ),
+        }),
+      })
+
+      const store = configureStore({
+        reducer: slice.reducer,
+      })
+      await store.dispatch(slice.actions.thunkReducers('test'))
+      expect(store.getState()).toMatchObject([
+        [
+          'pendingReducer',
+          {
+            type: 'test/thunkReducers/pending',
+            payload: undefined,
+          },
+        ],
+        [
+          'rejectedReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+          },
+        ],
+        [
+          'settledReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+          },
+        ],
+      ])
+    })
+
+    test('with options', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            function payloadCreator(arg: string, api) {
+              return 'should not call this'
+            },
+            {
+              options: {
+                condition() {
+                  return false
+                },
+                dispatchConditionRejection: true,
+              },
+              pending,
+              fulfilled,
+              rejected,
+              settled,
+            },
+          ),
+        }),
+      })
+
+      const store = configureStore({
+        reducer: slice.reducer,
+      })
+      await store.dispatch(slice.actions.thunkReducers('test'))
+      expect(store.getState()).toMatchObject([
+        [
+          'rejectedReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+            meta: { condition: true },
+          },
+        ],
+        [
+          'settledReducer',
+          {
+            type: 'test/thunkReducers/rejected',
+            payload: undefined,
+            meta: { condition: true },
+          },
+        ],
+      ])
+    })
+
+    test('has caseReducers for the asyncThunk', async () => {
+      const slice = createAppSlice({
+        name: 'test',
+        initialState: [],
+        reducers: (create) => ({
+          thunkReducers: create.asyncThunk(
+            function payloadCreator(arg, api) {
+              return Promise.resolve('resolved payload')
+            },
+            { pending, fulfilled, settled },
+          ),
+        }),
+      })
+
+      expect(slice.caseReducers.thunkReducers.pending).toBe(pending)
+      expect(slice.caseReducers.thunkReducers.fulfilled).toBe(fulfilled)
+      expect(slice.caseReducers.thunkReducers.settled).toBe(settled)
+      // even though it is not defined above, this should at least be a no-op function to match the TypeScript typings
+      // and should be callable as a reducer even if it does nothing
+      expect(() =>
+        slice.caseReducers.thunkReducers.rejected(
+          [],
+          slice.actions.thunkReducers.rejected(
+            new Error('test'),
+            'fakeRequestId',
+          ),
+        ),
+      ).not.toThrow()
+    })
+
+    test('can define reducer with prepare statement using create.preparedReducer', async () => {
+      const slice = createSlice({
+        name: 'test',
+        initialState: [] as any[],
+        reducers: (create) => ({
+          prepared: create.preparedReducer(
+            (p: string, m: number, e: { message: string }) => ({
+              payload: p,
+              meta: m,
+              error: e,
+            }),
+            (state, action) => {
+              state.push(action)
+            },
+          ),
+        }),
+      })
+
+      expect(
+        slice.reducer(
+          [],
+          slice.actions.prepared('test', 1, { message: 'err' }),
+        ),
+      ).toMatchInlineSnapshot(`
+        [
+          {
+            "error": {
+              "message": "err",
+            },
+            "meta": 1,
+            "payload": "test",
+            "type": "test/prepared",
+          },
+        ]
+      `)
+    })
+
+    test('throws an error when invoked with a normal `prepare` object that has not gone through a `create.preparedReducer` call', async () => {
+      expect(() =>
+        createSlice({
+          name: 'test',
+          initialState: [] as any[],
+          reducers: (create) => ({
+            prepared: {
+              prepare: (p: string, m: number, e: { message: string }) => ({
+                payload: p,
+                meta: m,
+                error: e,
+              }),
+              reducer: (state, action) => {
+                state.push(action)
+              },
+            },
+          }),
+        }),
+      ).toThrowErrorMatchingInlineSnapshot(
+        `[Error: Please use the \`create.preparedReducer\` notation for prepared action creators with the \`create\` notation.]`,
+      )
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/getDefaultEnhancers.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/getDefaultEnhancers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/getDefaultEnhancers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,143 @@
+import type { StoreEnhancer } from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+
+declare const enhancer1: StoreEnhancer<
+  {
+    has1: true
+  },
+  { stateHas1: true }
+>
+
+declare const enhancer2: StoreEnhancer<
+  {
+    has2: true
+  },
+  { stateHas2: true }
+>
+
+describe('type tests', () => {
+  test('prepend single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().prepend(enhancer1),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has2')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas2')
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().prepend(enhancer1, enhancer2),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('prepend multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().prepend([enhancer1, enhancer2] as const),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('concat single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat(enhancer1),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has2')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas2')
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat(enhancer1, enhancer2),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('concat multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat([enhancer1, enhancer2] as const),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+
+  test('concat and prepend', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      enhancers: (gDE) => gDE().concat(enhancer1).prepend(enhancer2),
+    })
+
+    expectTypeOf(store.has1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()
+
+    expectTypeOf(store.has2).toEqualTypeOf<true>()
+
+    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()
+
+    expectTypeOf(store).not.toHaveProperty('has3')
+
+    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,199 @@
+import { buildGetDefaultMiddleware } from '@internal/getDefaultMiddleware'
+import type {
+  Action,
+  Dispatch,
+  Middleware,
+  ThunkAction,
+  ThunkDispatch,
+  ThunkMiddleware,
+  Tuple,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+
+declare const middleware1: Middleware<{
+  (_: string): number
+}>
+
+declare const middleware2: Middleware<{
+  (_: number): string
+}>
+
+type ThunkReturn = Promise<'thunk'>
+declare const thunkCreator: () => () => ThunkReturn
+
+const getDefaultMiddleware = buildGetDefaultMiddleware()
+
+describe('type tests', () => {
+  test('prepend single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend(middleware1),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend(middleware1, middleware2),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('prepend multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().prepend([middleware1, middleware2] as const),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('concat single element', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat(middleware1),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('prepend multiple (rest)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat(middleware1, middleware2),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('concat multiple (array notation)', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat([middleware1, middleware2] as const),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('concat and prepend', () => {
+    const store = configureStore({
+      reducer: () => 0,
+      middleware: (gDM) => gDM().concat(middleware1).prepend(middleware2),
+    })
+
+    expectTypeOf(store.dispatch('foo')).toBeNumber()
+
+    expectTypeOf(store.dispatch(5)).toBeString()
+
+    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()
+
+    expectTypeOf(store.dispatch('foo')).not.toBeString()
+  })
+
+  test('allows passing options to thunk', () => {
+    const extraArgument = 42 as const
+
+    const m2 = getDefaultMiddleware({
+      thunk: false,
+    })
+
+    expectTypeOf(m2).toMatchTypeOf<Tuple<[]>>()
+
+    const dummyMiddleware: Middleware<
+      {
+        (action: Action<'actionListenerMiddleware/add'>): () => void
+      },
+      { counter: number }
+    > = (storeApi) => (next) => (action) => {
+      return next(action)
+    }
+
+    const dummyMiddleware2: Middleware<{}, { counter: number }> =
+      (storeApi) => (next) => (action) => {}
+
+    const testThunk: ThunkAction<
+      void,
+      { counter: number },
+      number,
+      UnknownAction
+    > = (dispatch, getState, extraArg) => {
+      expect(extraArg).toBe(extraArgument)
+    }
+
+    const reducer = () => ({ counter: 123 })
+
+    const store = configureStore({
+      reducer,
+      middleware: (gDM) => {
+        const middleware = gDM({
+          thunk: { extraArgument },
+          immutableCheck: false,
+          serializableCheck: false,
+          actionCreatorCheck: false,
+        })
+
+        const m3 = middleware.concat(dummyMiddleware, dummyMiddleware2)
+
+        expectTypeOf(m3).toMatchTypeOf<
+          Tuple<
+            [
+              ThunkMiddleware<any, UnknownAction, 42>,
+              Middleware<
+                (action: Action<'actionListenerMiddleware/add'>) => () => void,
+                {
+                  counter: number
+                },
+                Dispatch<UnknownAction>
+              >,
+              Middleware<{}, any, Dispatch<UnknownAction>>,
+            ]
+          >
+        >()
+
+        return m3
+      },
+    })
+
+    expectTypeOf(store.dispatch).toMatchTypeOf<
+      ThunkDispatch<any, 42, UnknownAction> & Dispatch<UnknownAction>
+    >()
+
+    store.dispatch(testThunk)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/getDefaultMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,317 @@
+import { Tuple } from '@internal/utils'
+import type {
+  Action,
+  Middleware,
+  ThunkAction,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+import { thunk } from 'redux-thunk'
+import { vi } from 'vitest'
+
+import { buildGetDefaultMiddleware } from '@internal/getDefaultMiddleware'
+
+const getDefaultMiddleware = buildGetDefaultMiddleware()
+
+describe('getDefaultMiddleware', () => {
+  afterEach(() => {
+    vi.unstubAllEnvs()
+  })
+
+  describe('Production behavior', () => {
+    beforeEach(() => {
+      vi.resetModules()
+    })
+
+    it('returns an array with only redux-thunk in production', async () => {
+      vi.stubEnv('NODE_ENV', 'production')
+
+      const { thunk } = await import('redux-thunk')
+      const { buildGetDefaultMiddleware } = await import(
+        '@internal/getDefaultMiddleware'
+      )
+
+      const middleware = buildGetDefaultMiddleware()()
+      expect(middleware).toContain(thunk)
+      expect(middleware.length).toBe(1)
+    })
+  })
+
+  it('returns an array with additional middleware in development', () => {
+    const middleware = getDefaultMiddleware()
+    expect(middleware).toContain(thunk)
+    expect(middleware.length).toBeGreaterThan(1)
+  })
+
+  const defaultMiddleware = getDefaultMiddleware()
+
+  it('removes the thunk middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ thunk: false })
+    // @ts-ignore
+    expect(middleware.includes(thunk)).toBe(false)
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('removes the immutable middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ immutableCheck: false })
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('removes the serializable middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ serializableCheck: false })
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('removes the action creator middleware if disabled', () => {
+    const middleware = getDefaultMiddleware({ actionCreatorCheck: false })
+    expect(middleware.length).toBe(defaultMiddleware.length - 1)
+  })
+
+  it('allows passing options to thunk', () => {
+    const extraArgument = 42 as const
+
+    const m2 = getDefaultMiddleware({
+      thunk: false,
+    })
+
+    const dummyMiddleware: Middleware<
+      {
+        (action: Action<'actionListenerMiddleware/add'>): () => void
+      },
+      { counter: number }
+    > = (storeApi) => (next) => (action) => {
+      return next(action)
+    }
+
+    const dummyMiddleware2: Middleware<{}, { counter: number }> =
+      (storeApi) => (next) => (action) => {}
+
+    const testThunk: ThunkAction<
+      void,
+      { counter: number },
+      number,
+      UnknownAction
+    > = (dispatch, getState, extraArg) => {
+      expect(extraArg).toBe(extraArgument)
+    }
+
+    const reducer = () => ({ counter: 123 })
+
+    const store = configureStore({
+      reducer,
+      middleware: (gDM) => {
+        const middleware = gDM({
+          thunk: { extraArgument },
+          immutableCheck: false,
+          serializableCheck: false,
+          actionCreatorCheck: false,
+        })
+
+        const m3 = middleware.concat(dummyMiddleware, dummyMiddleware2)
+
+        return m3
+      },
+    })
+
+    store.dispatch(testThunk)
+  })
+
+  it('allows passing options to immutableCheck', () => {
+    let immutableCheckWasCalled = false
+
+    const middleware = () =>
+      getDefaultMiddleware({
+        thunk: false,
+        immutableCheck: {
+          isImmutable: () => {
+            immutableCheckWasCalled = true
+            return true
+          },
+        },
+        serializableCheck: false,
+        actionCreatorCheck: false,
+      })
+
+    const reducer = () => ({})
+
+    const store = configureStore({
+      reducer,
+      middleware,
+    })
+
+    expect(immutableCheckWasCalled).toBe(true)
+  })
+
+  it('allows passing options to serializableCheck', () => {
+    let serializableCheckWasCalled = false
+
+    const middleware = () =>
+      getDefaultMiddleware({
+        thunk: false,
+        immutableCheck: false,
+        serializableCheck: {
+          isSerializable: () => {
+            serializableCheckWasCalled = true
+            return true
+          },
+        },
+        actionCreatorCheck: false,
+      })
+
+    const reducer = () => ({})
+
+    const store = configureStore({
+      reducer,
+      middleware,
+    })
+
+    store.dispatch({ type: 'TEST_ACTION' })
+
+    expect(serializableCheckWasCalled).toBe(true)
+  })
+})
+
+it('allows passing options to actionCreatorCheck', () => {
+  let actionCreatorCheckWasCalled = false
+
+  const middleware = () =>
+    getDefaultMiddleware({
+      thunk: false,
+      immutableCheck: false,
+      serializableCheck: false,
+      actionCreatorCheck: {
+        isActionCreator: (action: unknown): action is Function => {
+          actionCreatorCheckWasCalled = true
+          return false
+        },
+      },
+    })
+
+  const reducer = () => ({})
+
+  const store = configureStore({
+    reducer,
+    middleware,
+  })
+
+  store.dispatch({ type: 'TEST_ACTION' })
+
+  expect(actionCreatorCheckWasCalled).toBe(true)
+})
+
+describe('Tuple functionality', () => {
+  const middleware1: Middleware = () => (next) => (action) => next(action)
+  const middleware2: Middleware = () => (next) => (action) => next(action)
+  const defaultMiddleware = getDefaultMiddleware()
+  const originalDefaultMiddleware = [...defaultMiddleware]
+
+  test('allows to prepend a single value', () => {
+    const prepended = defaultMiddleware.prepend(middleware1)
+
+    // value is prepended
+    expect(prepended).toEqual([middleware1, ...defaultMiddleware])
+    // returned value is of correct type
+    expect(prepended).toBeInstanceOf(Tuple)
+    // prepended is a new array
+    expect(prepended).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to prepend multiple values (array as first argument)', () => {
+    const prepended = defaultMiddleware.prepend([middleware1, middleware2])
+
+    // value is prepended
+    expect(prepended).toEqual([middleware1, middleware2, ...defaultMiddleware])
+    // returned value is of correct type
+    expect(prepended).toBeInstanceOf(Tuple)
+    // prepended is a new array
+    expect(prepended).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to prepend multiple values (rest)', () => {
+    const prepended = defaultMiddleware.prepend(middleware1, middleware2)
+
+    // value is prepended
+    expect(prepended).toEqual([middleware1, middleware2, ...defaultMiddleware])
+    // returned value is of correct type
+    expect(prepended).toBeInstanceOf(Tuple)
+    // prepended is a new array
+    expect(prepended).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat a single value', () => {
+    const concatenated = defaultMiddleware.concat(middleware1)
+
+    // value is concatenated
+    expect(concatenated).toEqual([...defaultMiddleware, middleware1])
+    // returned value is of correct type
+    expect(concatenated).toBeInstanceOf(Tuple)
+    // concatenated is a new array
+    expect(concatenated).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat multiple values (array as first argument)', () => {
+    const concatenated = defaultMiddleware.concat([middleware1, middleware2])
+
+    // value is concatenated
+    expect(concatenated).toEqual([
+      ...defaultMiddleware,
+      middleware1,
+      middleware2,
+    ])
+    // returned value is of correct type
+    expect(concatenated).toBeInstanceOf(Tuple)
+    // concatenated is a new array
+    expect(concatenated).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat multiple values (rest)', () => {
+    const concatenated = defaultMiddleware.concat(middleware1, middleware2)
+
+    // value is concatenated
+    expect(concatenated).toEqual([
+      ...defaultMiddleware,
+      middleware1,
+      middleware2,
+    ])
+    // returned value is of correct type
+    expect(concatenated).toBeInstanceOf(Tuple)
+    // concatenated is a new array
+    expect(concatenated).not.toEqual(defaultMiddleware)
+    // defaultMiddleware is not modified
+    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)
+  })
+
+  test('allows to concat and then prepend', () => {
+    const concatenated = defaultMiddleware
+      .concat(middleware1)
+      .prepend(middleware2)
+
+    expect(concatenated).toEqual([
+      middleware2,
+      ...defaultMiddleware,
+      middleware1,
+    ])
+  })
+
+  test('allows to prepend and then concat', () => {
+    const concatenated = defaultMiddleware
+      .prepend(middleware2)
+      .concat(middleware1)
+
+    expect(concatenated).toEqual([
+      middleware2,
+      ...defaultMiddleware,
+      middleware1,
+    ])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,506 @@
+import { trackForMutations } from '@internal/immutableStateInvariantMiddleware'
+import { noop } from '@internal/listenerMiddleware/utils'
+import type {
+  ImmutableStateInvariantMiddlewareOptions,
+  Middleware,
+  MiddlewareAPI,
+  Store,
+} from '@reduxjs/toolkit'
+import {
+  createImmutableStateInvariantMiddleware,
+  isImmutableDefault,
+} from '@reduxjs/toolkit'
+
+type MWNext = Parameters<ReturnType<Middleware>>[0]
+
+describe('createImmutableStateInvariantMiddleware', () => {
+  let state: { foo: { bar: number[]; baz: string } }
+  const getState: Store['getState'] = () => state
+
+  function middleware(options: ImmutableStateInvariantMiddlewareOptions = {}) {
+    return createImmutableStateInvariantMiddleware(options)({
+      getState,
+    } as MiddlewareAPI)
+  }
+
+  beforeEach(() => {
+    state = { foo: { bar: [2, 3, 4], baz: 'baz' } }
+  })
+
+  it('sends the action through the middleware chain', () => {
+    const next: MWNext = vi.fn()
+    const dispatch = middleware()(next)
+    dispatch({ type: 'SOME_ACTION' })
+
+    expect(next).toHaveBeenCalledWith({
+      type: 'SOME_ACTION',
+    })
+  })
+
+  it('throws if mutating inside the dispatch', () => {
+    const next: MWNext = (action) => {
+      state.foo.bar.push(5)
+      return action
+    }
+
+    const dispatch = middleware()(next)
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION' })
+    }).toThrow(new RegExp('foo\\.bar\\.3'))
+  })
+
+  it('throws if mutating between dispatches', () => {
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware()(next)
+
+    dispatch({ type: 'SOME_ACTION' })
+    state.foo.bar.push(5)
+    expect(() => {
+      dispatch({ type: 'SOME_OTHER_ACTION' })
+    }).toThrow(new RegExp('foo\\.bar\\.3'))
+  })
+
+  it('does not throw if not mutating inside the dispatch', () => {
+    const next: MWNext = (action) => {
+      state = { ...state, foo: { ...state.foo, baz: 'changed!' } }
+      return action
+    }
+
+    const dispatch = middleware()(next)
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('does not throw if not mutating between dispatches', () => {
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware()(next)
+
+    dispatch({ type: 'SOME_ACTION' })
+    state = { ...state, foo: { ...state.foo, baz: 'changed!' } }
+    expect(() => {
+      dispatch({ type: 'SOME_OTHER_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('works correctly with circular references', () => {
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware()(next)
+
+    let x: any = {}
+    let y: any = {}
+    x.y = y
+    y.x = x
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION', x })
+    }).not.toThrow()
+  })
+
+  it('respects "isImmutable" option', function () {
+    const isImmutable = (value: any) => true
+    const next: MWNext = (action) => {
+      state.foo.bar.push(5)
+      return action
+    }
+
+    const dispatch = middleware({ isImmutable })(next)
+
+    expect(() => {
+      dispatch({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('respects "ignoredPaths" option', () => {
+    const next: MWNext = (action) => {
+      state.foo.bar.push(5)
+      return action
+    }
+
+    const dispatch1 = middleware({ ignoredPaths: ['foo.bar'] })(next)
+
+    expect(() => {
+      dispatch1({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+
+    const dispatch2 = middleware({ ignoredPaths: [/^foo/] })(next)
+
+    expect(() => {
+      dispatch2({ type: 'SOME_ACTION' })
+    }).not.toThrow()
+  })
+
+  it('Should print a warning if execution takes too long', () => {
+    state.foo.bar = new Array(10000).fill({ value: 'more' })
+
+    const next: MWNext = (action) => action
+
+    const dispatch = middleware({ warnAfter: 4 })(next)
+
+    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+    try {
+      dispatch({ type: 'SOME_ACTION' })
+
+      expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+      expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+        expect.stringMatching(
+          /^ImmutableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./,
+        ),
+      )
+    } finally {
+      consoleWarnSpy.mockRestore()
+    }
+  })
+
+  it('Should not print a warning if "next" takes too long', () => {
+    const next: MWNext = (action) => {
+      const started = Date.now()
+      while (Date.now() - started < 8) {}
+      return action
+    }
+
+    const dispatch = middleware({ warnAfter: 4 })(next)
+
+    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+    try {
+      dispatch({ type: 'SOME_ACTION' })
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+    } finally {
+      consoleWarnSpy.mockRestore()
+    }
+  })
+})
+
+describe('trackForMutations', () => {
+  function testCasesForMutation(spec: any) {
+    it('returns true and the mutated path', () => {
+      const state = spec.getState()
+      const options = spec.middlewareOptions || {}
+      const { isImmutable = isImmutableDefault, ignoredPaths } = options
+      const tracker = trackForMutations(isImmutable, ignoredPaths, state)
+      const newState = spec.fn(state)
+
+      expect(tracker.detectMutations()).toEqual({
+        wasMutated: true,
+        path: spec.path.join('.'),
+      })
+    })
+  }
+
+  function testCasesForNonMutation(spec: any) {
+    it('returns false', () => {
+      const state = spec.getState()
+      const options = spec.middlewareOptions || {}
+      const { isImmutable = isImmutableDefault, ignoredPaths } = options
+      const tracker = trackForMutations(isImmutable, ignoredPaths, state)
+      const newState = spec.fn(state)
+
+      expect(tracker.detectMutations()).toEqual({ wasMutated: false })
+    })
+  }
+
+  interface TestConfig {
+    getState: Store['getState']
+    fn: (s: any) => typeof s | object
+    middlewareOptions?: ImmutableStateInvariantMiddlewareOptions
+    path?: string[]
+  }
+
+  const mutations: Record<string, TestConfig> = {
+    'adding to nested array': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.foo.bar.push(5)
+        return s
+      },
+      path: ['foo', 'bar', '3'],
+    },
+    'adding to nested array and setting new root object': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.foo.bar.push(5)
+        return { ...s }
+      },
+      path: ['foo', 'bar', '3'],
+    },
+    'changing nested string': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.foo.baz = 'changed!'
+        return s
+      },
+      path: ['foo', 'baz'],
+    },
+    'removing nested state': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        delete s.foo
+        return s
+      },
+      path: ['foo'],
+    },
+    'adding to array': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.stuff.push(1)
+        return s
+      },
+      path: ['stuff', '0'],
+    },
+    'adding object to array': {
+      getState: () => ({
+        stuff: [],
+      }),
+      fn: (s) => {
+        s.stuff.push({ foo: 1, bar: 2 })
+        return s
+      },
+      path: ['stuff', '0'],
+    },
+    'mutating previous state and returning new state': {
+      getState: () => ({ counter: 0 }),
+      fn: (s) => {
+        s.mutation = true
+        return { ...s, counter: s.counter + 1 }
+      },
+      path: ['mutation'],
+    },
+    'mutating previous state with non immutable type and returning new state': {
+      getState: () => ({ counter: 0 }),
+      fn: (s) => {
+        s.mutation = [1, 2, 3]
+        return { ...s, counter: s.counter + 1 }
+      },
+      path: ['mutation'],
+    },
+    'mutating previous state with non immutable type and returning new state without that property':
+      {
+        getState: () => ({ counter: 0 }),
+        fn: (s) => {
+          s.mutation = [1, 2, 3]
+          return { counter: s.counter + 1 }
+        },
+        path: ['mutation'],
+      },
+    'mutating previous state with non immutable type and returning new simple state':
+      {
+        getState: () => ({ counter: 0 }),
+        fn: (s) => {
+          s.mutation = [1, 2, 3]
+          return 1
+        },
+        path: ['mutation'],
+      },
+    'mutating previous state by deleting property and returning new state without that property':
+      {
+        getState: () => ({ counter: 0, toBeDeleted: true }),
+        fn: (s) => {
+          delete s.toBeDeleted
+          return { counter: s.counter + 1 }
+        },
+        path: ['toBeDeleted'],
+      },
+    'mutating previous state by deleting nested property': {
+      getState: () => ({ nested: { counter: 0, toBeDeleted: true }, foo: 1 }),
+      fn: (s) => {
+        delete s.nested.toBeDeleted
+        return { nested: { counter: s.counter + 1 } }
+      },
+      path: ['nested', 'toBeDeleted'],
+    },
+    'update reference': {
+      getState: () => ({ foo: {} }),
+      fn: (s) => {
+        s.foo = {}
+        return s
+      },
+      path: ['foo'],
+    },
+    'cannot ignore root state': {
+      getState: () => ({ foo: {} }),
+      fn: (s) => {
+        s.foo = {}
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: [''],
+      },
+      path: ['foo'],
+    },
+    'catching state mutation in non-ignored branch': {
+      getState: () => ({
+        foo: {
+          bar: [1, 2],
+        },
+        boo: {
+          yah: [1, 2],
+        },
+      }),
+      fn: (s) => {
+        s.foo.bar.push(3)
+        s.boo.yah.push(3)
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['foo'],
+      },
+      path: ['boo', 'yah', '2'],
+    },
+  }
+
+  Object.keys(mutations).forEach((mutationDesc) => {
+    describe(mutationDesc, () => {
+      testCasesForMutation(mutations[mutationDesc])
+    })
+  })
+
+  const nonMutations: Record<string, TestConfig> = {
+    'not doing anything': {
+      getState: () => ({ a: 1, b: 2 }),
+      fn: (s) => s,
+    },
+    'from undefined to something': {
+      getState: () => undefined,
+      fn: (s) => ({ foo: 'bar' }),
+    },
+    'returning same state': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => s,
+    },
+    'returning a new state object with nested new string': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        return { ...s, foo: { ...s.foo, baz: 'changed!' } }
+      },
+    },
+    'returning a new state object with nested new array': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        return { ...s, foo: { ...s.foo, bar: [...s.foo.bar, 5] } }
+      },
+    },
+    'removing nested state': {
+      getState: () => ({
+        foo: {
+          bar: [2, 3, 4],
+          baz: 'baz',
+        },
+        stuff: [],
+      }),
+      fn: (s) => {
+        return { ...s, foo: {} }
+      },
+    },
+    'having a NaN in the state': {
+      getState: () => ({ a: NaN, b: Number.NaN }),
+      fn: (s) => s,
+    },
+    'ignoring branches from mutation detection': {
+      getState: () => ({
+        foo: {
+          bar: 'bar',
+        },
+      }),
+      fn: (s) => {
+        s.foo.bar = 'baz'
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['foo'],
+      },
+    },
+    'ignoring nested branches from mutation detection': {
+      getState: () => ({
+        foo: {
+          bar: [1, 2],
+          boo: {
+            yah: [1, 2],
+          },
+        },
+      }),
+      fn: (s) => {
+        s.foo.bar.push(3)
+        s.foo.boo.yah.push(3)
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['foo.bar', 'foo.boo.yah'],
+      },
+    },
+    'ignoring nested array indices from mutation detection': {
+      getState: () => ({
+        stuff: [{ a: 1 }, { a: 2 }],
+      }),
+      fn: (s) => {
+        s.stuff[1].a = 3
+        return s
+      },
+      middlewareOptions: {
+        ignoredPaths: ['stuff.1'],
+      },
+    },
+  }
+
+  Object.keys(nonMutations).forEach((nonMutationDesc) => {
+    describe(nonMutationDesc, () => {
+      testCasesForNonMutation(nonMutations[nonMutationDesc])
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/mapBuilders.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/mapBuilders.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/mapBuilders.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,416 @@
+import type { SerializedError } from '@internal/createAsyncThunk'
+import { createAsyncThunk } from '@internal/createAsyncThunk'
+import { executeReducerBuilderCallback } from '@internal/mapBuilders'
+import type { UnknownAction } from '@reduxjs/toolkit'
+import { createAction } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('builder callback for actionMap', () => {
+    const increment = createAction<number, 'increment'>('increment')
+
+    const decrement = createAction<number, 'decrement'>('decrement')
+
+    executeReducerBuilderCallback<number>((builder) => {
+      builder.addCase(increment, (state, action) => {
+        expectTypeOf(state).toBeNumber()
+
+        expectTypeOf(action).toEqualTypeOf<{
+          type: 'increment'
+          payload: number
+        }>()
+
+        expectTypeOf(state).not.toBeString()
+
+        expectTypeOf(action).not.toMatchTypeOf<{
+          type: 'increment'
+          payload: string
+        }>()
+
+        expectTypeOf(action).not.toMatchTypeOf<{
+          type: 'decrement'
+          payload: number
+        }>()
+      })
+
+      builder.addCase('increment', (state, action) => {
+        expectTypeOf(state).toBeNumber()
+
+        expectTypeOf(action).toEqualTypeOf<{ type: 'increment' }>()
+
+        expectTypeOf(state).not.toBeString()
+
+        expectTypeOf(action).not.toMatchTypeOf<{ type: 'decrement' }>()
+
+        // this cannot be inferred and has to be manually specified
+        expectTypeOf(action).not.toMatchTypeOf<{
+          type: 'increment'
+          payload: number
+        }>()
+      })
+
+      builder.addCase(
+        increment,
+        (state, action: ReturnType<typeof increment>) => state,
+      )
+
+      // @ts-expect-error
+      builder.addCase(
+        increment,
+        (state, action: ReturnType<typeof decrement>) => state,
+      )
+
+      builder.addCase(
+        'increment',
+        (state, action: ReturnType<typeof increment>) => state,
+      )
+
+      // @ts-expect-error
+      builder.addCase(
+        'decrement',
+        (state, action: ReturnType<typeof increment>) => state,
+      )
+
+      // action type is inferred
+      builder.addMatcher(increment.match, (state, action) => {
+        expectTypeOf(action).toEqualTypeOf<ReturnType<typeof increment>>()
+      })
+
+      test('action type is inferred when type predicate lacks `type` property', () => {
+        type PredicateWithoutTypeProperty = {
+          payload: number
+        }
+
+        builder.addMatcher(
+          (action): action is PredicateWithoutTypeProperty => true,
+          (state, action) => {
+            expectTypeOf(action).toMatchTypeOf<PredicateWithoutTypeProperty>()
+
+            expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+          },
+        )
+      })
+
+      // action type defaults to UnknownAction if no type predicate matcher is passed
+      builder.addMatcher(
+        () => true,
+        (state, action) => {
+          expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+        },
+      )
+
+      // with a boolean checker, action can also be typed by type argument
+      builder.addMatcher<{ foo: boolean }>(
+        () => true,
+        (state, action) => {
+          expectTypeOf(action).toMatchTypeOf<{ foo: boolean }>()
+
+          expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+        },
+      )
+
+      // addCase().addMatcher() is possible, action type inferred correctly
+      builder
+        .addCase(
+          'increment',
+          (state, action: ReturnType<typeof increment>) => state,
+        )
+        .addMatcher(decrement.match, (state, action) => {
+          expectTypeOf(action).toEqualTypeOf<ReturnType<typeof decrement>>()
+        })
+
+      // addCase().addDefaultCase() is possible, action type is UnknownAction
+      builder
+        .addCase(
+          'increment',
+          (state, action: ReturnType<typeof increment>) => state,
+        )
+        .addDefaultCase((state, action) => {
+          expectTypeOf(action).toMatchTypeOf<UnknownAction>()
+        })
+
+      test('addAsyncThunk() should prevent further calls to addCase() ', () => {
+        const asyncThunk = createAsyncThunk('test', () => {})
+        const b = builder.addAsyncThunk(asyncThunk, {
+          pending: () => {},
+          rejected: () => {},
+          fulfilled: () => {},
+          settled: () => {},
+        })
+
+        expectTypeOf(b).not.toHaveProperty('addCase')
+
+        expectTypeOf(b.addAsyncThunk).toBeFunction()
+
+        expectTypeOf(b.addMatcher).toBeCallableWith(increment.match, () => {})
+
+        expectTypeOf(b.addDefaultCase).toBeCallableWith(() => {})
+      })
+
+      test('addMatcher() should prevent further calls to addCase() and addAsyncThunk()', () => {
+        const b = builder.addMatcher(increment.match, () => {})
+
+        expectTypeOf(b).not.toHaveProperty('addCase')
+        expectTypeOf(b).not.toHaveProperty('addAsyncThunk')
+
+        expectTypeOf(b.addMatcher).toBeCallableWith(increment.match, () => {})
+
+        expectTypeOf(b.addDefaultCase).toBeCallableWith(() => {})
+      })
+
+      test('addDefaultCase() should prevent further calls to addCase(), addAsyncThunk(), addMatcher() and addDefaultCase', () => {
+        const b = builder.addDefaultCase(() => {})
+
+        expectTypeOf(b).not.toHaveProperty('addCase')
+
+        expectTypeOf(b).not.toHaveProperty('addAsyncThunk')
+
+        expectTypeOf(b).not.toHaveProperty('addMatcher')
+
+        expectTypeOf(b).not.toHaveProperty('addDefaultCase')
+      })
+
+      describe('`createAsyncThunk` actions work with `mapBuilder`', () => {
+        test('case 1: normal `createAsyncThunk`', () => {
+          const thunk = createAsyncThunk('test', () => {
+            return 'ret' as const
+          })
+          builder.addCase(thunk.pending, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: undefined
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'pending'
+              }
+            }>()
+          })
+
+          builder.addCase(thunk.rejected, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: unknown
+              error: SerializedError
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'rejected'
+                aborted: boolean
+                condition: boolean
+                rejectedWithValue: boolean
+              }
+            }>()
+          })
+          builder.addCase(thunk.fulfilled, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: 'ret'
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'fulfilled'
+              }
+            }>()
+          })
+
+          builder.addAsyncThunk(thunk, {
+            pending(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: undefined
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'pending'
+                }
+              }>()
+            },
+            rejected(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: unknown
+                error: SerializedError
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'rejected'
+                  aborted: boolean
+                  condition: boolean
+                  rejectedWithValue: boolean
+                }
+              }>()
+            },
+            fulfilled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: 'ret'
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'fulfilled'
+                }
+              }>()
+            },
+            settled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<
+                | {
+                    payload: 'ret'
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'fulfilled'
+                    }
+                  }
+                | {
+                    payload: unknown
+                    error: SerializedError
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'rejected'
+                      aborted: boolean
+                      condition: boolean
+                      rejectedWithValue: boolean
+                    }
+                  }
+              >()
+            },
+          })
+        })
+
+        test('case 2: `createAsyncThunk` with `meta`', () => {
+          const thunk = createAsyncThunk<
+            'ret',
+            void,
+            {
+              pendingMeta: { startedTimeStamp: number }
+              fulfilledMeta: {
+                fulfilledTimeStamp: number
+                baseQueryMeta: 'meta!'
+              }
+              rejectedMeta: {
+                baseQueryMeta: 'meta!'
+              }
+            }
+          >(
+            'test',
+            (_, api) => {
+              return api.fulfillWithValue('ret' as const, {
+                fulfilledTimeStamp: 5,
+                baseQueryMeta: 'meta!',
+              })
+            },
+            {
+              getPendingMeta() {
+                return { startedTimeStamp: 0 }
+              },
+            },
+          )
+
+          builder.addCase(thunk.pending, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: undefined
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'pending'
+                startedTimeStamp: number
+              }
+            }>()
+          })
+
+          builder.addCase(thunk.rejected, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: unknown
+              error: SerializedError
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'rejected'
+                aborted: boolean
+                condition: boolean
+                rejectedWithValue: boolean
+                baseQueryMeta?: 'meta!'
+              }
+            }>()
+
+            if (action.meta.rejectedWithValue) {
+              expectTypeOf(action.meta.baseQueryMeta).toEqualTypeOf<'meta!'>()
+            }
+          })
+          builder.addCase(thunk.fulfilled, (_, action) => {
+            expectTypeOf(action).toMatchTypeOf<{
+              payload: 'ret'
+              meta: {
+                arg: void
+                requestId: string
+                requestStatus: 'fulfilled'
+                baseQueryMeta: 'meta!'
+              }
+            }>()
+          })
+
+          builder.addAsyncThunk(thunk, {
+            pending(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: undefined
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'pending'
+                  startedTimeStamp: number
+                }
+              }>()
+            },
+            rejected(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: unknown
+                error: SerializedError
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'rejected'
+                  aborted: boolean
+                  condition: boolean
+                  rejectedWithValue: boolean
+                  baseQueryMeta?: 'meta!'
+                }
+              }>()
+            },
+            fulfilled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<{
+                payload: 'ret'
+                meta: {
+                  arg: void
+                  requestId: string
+                  requestStatus: 'fulfilled'
+                  baseQueryMeta: 'meta!'
+                }
+              }>()
+            },
+            settled(_, action) {
+              expectTypeOf(action).toMatchTypeOf<
+                | {
+                    payload: 'ret'
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'fulfilled'
+                      baseQueryMeta: 'meta!'
+                    }
+                  }
+                | {
+                    payload: unknown
+                    error: SerializedError
+                    meta: {
+                      arg: void
+                      requestId: string
+                      requestStatus: 'rejected'
+                      aborted: boolean
+                      condition: boolean
+                      rejectedWithValue: boolean
+                      baseQueryMeta?: 'meta!'
+                    }
+                  }
+              >()
+            },
+          })
+        })
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/matchers.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/matchers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/matchers.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,296 @@
+import type { UnknownAction } from 'redux'
+import type { SerializedError } from '../../src'
+import {
+  createAction,
+  createAsyncThunk,
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isFulfilled,
+  isPending,
+  isRejected,
+  isRejectedWithValue,
+} from '../../src'
+
+const action: UnknownAction = { type: 'foo' }
+
+describe('type tests', () => {
+  describe('isAnyOf', () => {
+    test('isAnyOf correctly narrows types when used with action creators', () => {
+      const actionA = createAction('a', () => {
+        return {
+          payload: {
+            prop1: 1,
+            prop3: 2,
+          },
+        }
+      })
+
+      const actionB = createAction('b', () => {
+        return {
+          payload: {
+            prop1: 1,
+            prop2: 2,
+          },
+        }
+      })
+
+      if (isAnyOf(actionA, actionB)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop3')
+      }
+    })
+
+    test('isAnyOf correctly narrows types when used with async thunks', () => {
+      const asyncThunk1 = createAsyncThunk<{ prop1: number; prop3: number }>(
+        'asyncThunk1',
+
+        async () => {
+          return {
+            prop1: 1,
+            prop3: 3,
+          }
+        },
+      )
+
+      const asyncThunk2 = createAsyncThunk<{ prop1: number; prop2: number }>(
+        'asyncThunk2',
+
+        async () => {
+          return {
+            prop1: 1,
+            prop2: 2,
+          }
+        },
+      )
+
+      if (isAnyOf(asyncThunk1.fulfilled, asyncThunk2.fulfilled)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop3')
+      }
+    })
+
+    test('isAnyOf correctly narrows types when used with type guards', () => {
+      interface ActionA {
+        type: 'a'
+        payload: {
+          prop1: 1
+          prop3: 2
+        }
+      }
+
+      interface ActionB {
+        type: 'b'
+        payload: {
+          prop1: 1
+          prop2: 2
+        }
+      }
+
+      const guardA = (v: any): v is ActionA => {
+        return v.type === 'a'
+      }
+
+      const guardB = (v: any): v is ActionB => {
+        return v.type === 'b'
+      }
+
+      if (isAnyOf(guardA, guardB)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop3')
+      }
+    })
+  })
+
+  describe('isAllOf', () => {
+    interface SpecialAction {
+      payload: {
+        special: boolean
+      }
+    }
+
+    const isSpecialAction = (v: any): v is SpecialAction => {
+      return v.meta.isSpecial
+    }
+
+    test('isAllOf correctly narrows types when used with action creators and type guards', () => {
+      const actionA = createAction('a', () => {
+        return {
+          payload: {
+            prop1: 1,
+            prop3: 2,
+          },
+        }
+      })
+
+      if (isAllOf(actionA, isSpecialAction)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).toHaveProperty('prop3')
+
+        expectTypeOf(action.payload).toHaveProperty('special')
+      }
+    })
+
+    test('isAllOf correctly narrows types when used with async thunks and type guards', () => {
+      const asyncThunk1 = createAsyncThunk<{ prop1: number; prop3: number }>(
+        'asyncThunk1',
+
+        async () => {
+          return {
+            prop1: 1,
+            prop3: 3,
+          }
+        },
+      )
+
+      if (isAllOf(asyncThunk1.fulfilled, isSpecialAction)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).toHaveProperty('prop3')
+
+        expectTypeOf(action.payload).toHaveProperty('special')
+      }
+    })
+
+    test('isAnyOf correctly narrows types when used with type guards', () => {
+      interface ActionA {
+        type: 'a'
+        payload: {
+          prop1: 1
+          prop3: 2
+        }
+      }
+
+      const guardA = (v: any): v is ActionA => {
+        return v.type === 'a'
+      }
+
+      if (isAllOf(guardA, isSpecialAction)(action)) {
+        expectTypeOf(action.payload).toHaveProperty('prop1')
+
+        expectTypeOf(action.payload).not.toHaveProperty('prop2')
+
+        expectTypeOf(action.payload).toHaveProperty('prop3')
+
+        expectTypeOf(action.payload).toHaveProperty('special')
+      }
+    })
+
+    test('isPending correctly narrows types', () => {
+      if (isPending(action)) {
+        expectTypeOf(action.payload).toBeUndefined()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+
+      if (isPending(thunk)(action)) {
+        expectTypeOf(action.payload).toBeUndefined()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+    })
+
+    test('isRejected correctly narrows types', () => {
+      if (isRejected(action)) {
+        // might be there if rejected with payload
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+
+      if (isRejected(thunk)(action)) {
+        // might be there if rejected with payload
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+    })
+
+    test('isFulfilled correctly narrows types', () => {
+      if (isFulfilled(action)) {
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+      if (isFulfilled(thunk)(action)) {
+        expectTypeOf(action.payload).toBeString()
+
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+    })
+
+    test('isAsyncThunkAction correctly narrows types', () => {
+      if (isAsyncThunkAction(action)) {
+        expectTypeOf(action.payload).toBeUnknown()
+
+        // do not expect an error property because pending/fulfilled lack it
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+
+      const thunk = createAsyncThunk<string>('a', () => 'result')
+      if (isAsyncThunkAction(thunk)(action)) {
+        // we should expect the payload to be available, but of unknown type because the action may be pending/rejected
+        expectTypeOf(action.payload).toBeUnknown()
+
+        // do not expect an error property because pending/fulfilled lack it
+        expectTypeOf(action).not.toHaveProperty('error')
+      }
+    })
+
+    test('isRejectedWithValue correctly narrows types', () => {
+      if (isRejectedWithValue(action)) {
+        expectTypeOf(action.payload).toBeUnknown()
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+
+      const thunk = createAsyncThunk<
+        string,
+        void,
+        { rejectValue: { message: string } }
+      >('a', () => 'result')
+      if (isRejectedWithValue(thunk)(action)) {
+        expectTypeOf(action.payload).toEqualTypeOf({ message: '' as string })
+
+        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+      }
+    })
+  })
+
+  test('matchersAcceptSpreadArguments', () => {
+    const thunk1 = createAsyncThunk('a', () => 'a')
+    const thunk2 = createAsyncThunk('b', () => 'b')
+    const interestingThunks = [thunk1, thunk2]
+    const interestingPendingThunks = interestingThunks.map(
+      (thunk) => thunk.pending,
+    )
+    const interestingFulfilledThunks = interestingThunks.map(
+      (thunk) => thunk.fulfilled,
+    )
+
+    const isLoading = isAnyOf(...interestingPendingThunks)
+    const isNotLoading = isAnyOf(...interestingFulfilledThunks)
+
+    const isAllLoading = isAllOf(...interestingPendingThunks)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/matchers.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/matchers.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/matchers.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,461 @@
+import { vi } from 'vitest'
+import type { ThunkAction, UnknownAction } from '@reduxjs/toolkit'
+import {
+  isAllOf,
+  isAnyOf,
+  isAsyncThunkAction,
+  isFulfilled,
+  isPending,
+  isRejected,
+  isRejectedWithValue,
+  createAction,
+  createAsyncThunk,
+  createReducer,
+} from '@reduxjs/toolkit'
+
+const thunk: ThunkAction<any, any, any, UnknownAction> = () => {}
+
+describe('isAnyOf', () => {
+  it('returns true only if any matchers match (match function)', () => {
+    const actionA = createAction<string>('a')
+    const actionB = createAction<number>('b')
+
+    const trueAction = {
+      type: 'a',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(actionA, actionB)(trueAction)).toEqual(true)
+
+    const falseAction = {
+      type: 'c',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(actionA, actionB)(falseAction)).toEqual(false)
+  })
+
+  it('returns true only if any type guards match', () => {
+    const actionA = createAction<string>('a')
+    const actionB = createAction<number>('b')
+
+    const isActionA = actionA.match
+    const isActionB = actionB.match
+
+    const trueAction = {
+      type: 'a',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(isActionA, isActionB)(trueAction)).toEqual(true)
+
+    const falseAction = {
+      type: 'c',
+      payload: 'payload',
+    }
+
+    expect(isAnyOf(isActionA, isActionB)(falseAction)).toEqual(false)
+  })
+
+  it('returns true only if any matchers match (thunk action creators)', () => {
+    const thunkA = createAsyncThunk<string>('a', () => {
+      return 'noop'
+    })
+    const thunkB = createAsyncThunk<number>('b', () => {
+      return 0
+    })
+
+    const action = thunkA.fulfilled('fakeRequestId', 'test')
+
+    expect(isAnyOf(thunkA.fulfilled, thunkB.fulfilled)(action)).toEqual(true)
+
+    expect(
+      isAnyOf(thunkA.pending, thunkA.rejected, thunkB.fulfilled)(action),
+    ).toEqual(false)
+  })
+
+  it('works with reducers', () => {
+    const actionA = createAction<string>('a')
+    const actionB = createAction<number>('b')
+
+    const trueAction = {
+      type: 'a',
+      payload: 'payload',
+    }
+
+    const initialState = { value: false }
+
+    const reducer = createReducer(initialState, (builder) => {
+      builder.addMatcher(isAnyOf(actionA, actionB), (state) => {
+        return { ...state, value: true }
+      })
+    })
+
+    expect(reducer(initialState, trueAction)).toEqual({ value: true })
+
+    const falseAction = {
+      type: 'c',
+      payload: 'payload',
+    }
+
+    expect(reducer(initialState, falseAction)).toEqual(initialState)
+  })
+})
+
+describe('isAllOf', () => {
+  it('returns true only if all matchers match', () => {
+    const actionA = createAction<string>('a')
+
+    interface SpecialAction {
+      payload: 'SPECIAL'
+    }
+
+    const isActionSpecial = (action: any): action is SpecialAction => {
+      return action.payload === 'SPECIAL'
+    }
+
+    const trueAction = {
+      type: 'a',
+      payload: 'SPECIAL',
+    }
+
+    expect(isAllOf(actionA, isActionSpecial)(trueAction)).toEqual(true)
+
+    const falseAction = {
+      type: 'a',
+      payload: 'ORDINARY',
+    }
+
+    expect(isAllOf(actionA, isActionSpecial)(falseAction)).toEqual(false)
+
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+
+    const specialThunkAction = thunkA.fulfilled('SPECIAL', 'fakeRequestId')
+
+    expect(isAllOf(thunkA.fulfilled, isActionSpecial)(specialThunkAction)).toBe(
+      true,
+    )
+
+    const ordinaryThunkAction = thunkA.fulfilled('ORDINARY', 'fakeRequestId')
+
+    expect(
+      isAllOf(thunkA.fulfilled, isActionSpecial)(ordinaryThunkAction),
+    ).toBe(false)
+  })
+})
+
+describe('isPending', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isPending()(action)).toBe(false)
+    expect(isPending(action)).toBe(false)
+    expect(isPending(thunk)).toBe(false)
+  })
+
+  test('should return true only for pending async thunk actions', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isPending()(pendingAction)).toBe(true)
+    expect(isPending(pendingAction)).toBe(true)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isPending()(rejectedAction)).toBe(false)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isPending()(fulfilledAction)).toBe(false)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isPending(thunkA, thunkC)
+    const matchB = isPending(thunkB)
+
+    function testPendingAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(expected)
+      expect(matchB(pendingAction)).toBe(!expected)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(false)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(false)
+    }
+
+    testPendingAction(thunkA, true)
+    testPendingAction(thunkC, true)
+    testPendingAction(thunkB, false)
+  })
+})
+
+describe('isRejected', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isRejected()(action)).toBe(false)
+    expect(isRejected(action)).toBe(false)
+    expect(isRejected(thunk)).toBe(false)
+  })
+
+  test('should return true only for rejected async thunk actions', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isRejected()(pendingAction)).toBe(false)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isRejected()(rejectedAction)).toBe(true)
+    expect(isRejected(rejectedAction)).toBe(true)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isRejected()(fulfilledAction)).toBe(false)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isRejected(thunkA, thunkC)
+    const matchB = isRejected(thunkB)
+
+    function testRejectedAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(false)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(expected)
+      expect(matchB(rejectedAction)).toBe(!expected)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(false)
+    }
+
+    testRejectedAction(thunkA, true)
+    testRejectedAction(thunkC, true)
+    testRejectedAction(thunkB, false)
+  })
+})
+
+describe('isRejectedWithValue', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isRejectedWithValue()(action)).toBe(false)
+    expect(isRejectedWithValue(action)).toBe(false)
+    expect(isRejectedWithValue(thunk)).toBe(false)
+  })
+
+  test('should return true only for rejected-with-value async thunk actions', async () => {
+    const thunk = createAsyncThunk<string>('a', (_, { rejectWithValue }) => {
+      return rejectWithValue('rejectWithValue!')
+    })
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isRejectedWithValue()(pendingAction)).toBe(false)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isRejectedWithValue()(rejectedAction)).toBe(false)
+
+    const getState = vi.fn(() => ({}))
+    const dispatch = vi.fn((x: any) => x)
+    const extra = {}
+
+    // note: doesn't throw because we don't unwrap it
+    const rejectedWithValueAction = await thunk()(dispatch, getState, extra)
+
+    expect(isRejectedWithValue()(rejectedWithValueAction)).toBe(true)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isRejectedWithValue()(fulfilledAction)).toBe(false)
+  })
+
+  test('should return true only for thunks provided as arguments', async () => {
+    const payloadCreator = (_: any, { rejectWithValue }: any) => {
+      return rejectWithValue('rejectWithValue!')
+    }
+
+    const thunkA = createAsyncThunk<string>('a', payloadCreator)
+    const thunkB = createAsyncThunk<string>('b', payloadCreator)
+    const thunkC = createAsyncThunk<string>('c', payloadCreator)
+
+    const matchAC = isRejectedWithValue(thunkA, thunkC)
+    const matchB = isRejectedWithValue(thunkB)
+
+    async function testRejectedAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(false)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      // rejected-with-value is a narrower requirement than rejected
+      expect(matchAC(rejectedAction)).toBe(false)
+
+      const getState = vi.fn(() => ({}))
+      const dispatch = vi.fn((x: any) => x)
+      const extra = {}
+
+      // note: doesn't throw because we don't unwrap it
+      const rejectedWithValueAction = await thunk()(dispatch, getState, extra)
+
+      expect(matchAC(rejectedWithValueAction)).toBe(expected)
+      expect(matchB(rejectedWithValueAction)).toBe(!expected)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(false)
+    }
+
+    await testRejectedAction(thunkA, true)
+    await testRejectedAction(thunkC, true)
+    await testRejectedAction(thunkB, false)
+  })
+})
+
+describe('isFulfilled', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isFulfilled()(action)).toBe(false)
+    expect(isFulfilled(action)).toBe(false)
+    expect(isFulfilled(thunk)).toBe(false)
+  })
+
+  test('should return true only for fulfilled async thunk actions', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(isFulfilled()(pendingAction)).toBe(false)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(isFulfilled()(rejectedAction)).toBe(false)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(isFulfilled()(fulfilledAction)).toBe(true)
+    expect(isFulfilled(fulfilledAction)).toBe(true)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isFulfilled(thunkA, thunkC)
+    const matchB = isFulfilled(thunkB)
+
+    function testFulfilledAction(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(false)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(false)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(expected)
+      expect(matchB(fulfilledAction)).toBe(!expected)
+    }
+
+    testFulfilledAction(thunkA, true)
+    testFulfilledAction(thunkC, true)
+    testFulfilledAction(thunkB, false)
+  })
+})
+
+describe('isAsyncThunkAction', () => {
+  test('should return false for a regular action', () => {
+    const action = createAction<string>('action/type')('testPayload')
+
+    expect(isAsyncThunkAction()(action)).toBe(false)
+    expect(isAsyncThunkAction(action)).toBe(false)
+    expect(isAsyncThunkAction(thunk)).toBe(false)
+  })
+
+  test('should return true for any async thunk action if no arguments were provided', () => {
+    const thunk = createAsyncThunk<string>('a', () => 'result')
+    const matcher = isAsyncThunkAction()
+
+    const pendingAction = thunk.pending('fakeRequestId')
+    expect(matcher(pendingAction)).toBe(true)
+
+    const rejectedAction = thunk.rejected(
+      new Error('rejected'),
+      'fakeRequestId',
+    )
+    expect(matcher(rejectedAction)).toBe(true)
+
+    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+    expect(matcher(fulfilledAction)).toBe(true)
+  })
+
+  test('should return true only for thunks provided as arguments', () => {
+    const thunkA = createAsyncThunk<string>('a', () => 'result')
+    const thunkB = createAsyncThunk<string>('b', () => 'result')
+    const thunkC = createAsyncThunk<string>('c', () => 'result')
+
+    const matchAC = isAsyncThunkAction(thunkA, thunkC)
+    const matchB = isAsyncThunkAction(thunkB)
+
+    function testAllActions(
+      thunk: typeof thunkA | typeof thunkB | typeof thunkC,
+      expected: boolean,
+    ) {
+      const pendingAction = thunk.pending('fakeRequestId')
+      expect(matchAC(pendingAction)).toBe(expected)
+      expect(matchB(pendingAction)).toBe(!expected)
+
+      const rejectedAction = thunk.rejected(
+        new Error('rejected'),
+        'fakeRequestId',
+      )
+      expect(matchAC(rejectedAction)).toBe(expected)
+      expect(matchB(rejectedAction)).toBe(!expected)
+
+      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')
+      expect(matchAC(fulfilledAction)).toBe(expected)
+      expect(matchB(fulfilledAction)).toBe(!expected)
+    }
+
+    testAllActions(thunkA, true)
+    testAllActions(thunkC, true)
+    testAllActions(thunkB, false)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,663 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { isNestedFrozen } from '@internal/serializableStateInvariantMiddleware'
+import type { Reducer } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createNextState,
+  createSerializableStateInvariantMiddleware,
+  findNonSerializableValue,
+  isPlain,
+  Tuple,
+} from '@reduxjs/toolkit'
+
+// Mocking console
+const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+afterEach(() => {
+  vi.clearAllMocks()
+})
+
+afterAll(() => {
+  vi.restoreAllMocks()
+})
+
+describe('findNonSerializableValue', () => {
+  it('Should return false if no matching values are found', () => {
+    const obj = {
+      a: 42,
+      b: {
+        b1: 'test',
+      },
+      c: [99, { d: 123 }],
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toBe(false)
+  })
+
+  it('Should return a keypath and the value if it finds a non-serializable value', () => {
+    function testFunction() {}
+
+    const obj = {
+      a: 42,
+      b: {
+        b1: testFunction,
+      },
+      c: [99, { d: 123 }],
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toEqual({ keyPath: 'b.b1', value: testFunction })
+  })
+
+  it('Should return the first non-serializable value it finds', () => {
+    const map = new Map()
+    const symbol = Symbol.for('testSymbol')
+
+    const obj = {
+      a: 42,
+      b: {
+        b1: 1,
+      },
+      c: [99, { d: 123 }, map, symbol, 'test'],
+      d: symbol,
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toEqual({ keyPath: 'c.2', value: map })
+  })
+
+  it('Should return a specific value if the root object is non-serializable', () => {
+    const value = new Map()
+    const result = findNonSerializableValue(value)
+
+    expect(result).toEqual({ keyPath: '<root>', value })
+  })
+
+  it('Should accept null as a valid value', () => {
+    const obj = {
+      a: 42,
+      b: {
+        b1: 1,
+      },
+      c: null,
+    }
+
+    const result = findNonSerializableValue(obj)
+
+    expect(result).toEqual(false)
+  })
+})
+
+describe('serializableStateInvariantMiddleware', () => {
+  it('Should log an error when a non-serializable action is dispatched', () => {
+    const reducer: Reducer = (state = 0, _action) => state + 1
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware()
+
+    const store = configureStore({
+      reducer,
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    const symbol = Symbol.for('SOME_CONSTANT')
+    const dispatchedAction = { type: 'an-action', payload: symbol }
+
+    store.dispatch(dispatchedAction)
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `A non-serializable value was detected in an action, in the path: \`payload\`. Value:`,
+      symbol,
+      `\nTake a look at the logic that dispatched this action: `,
+      dispatchedAction,
+      `\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,
+      `\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,
+    )
+  })
+
+  it('Should log an error when a non-serializable value is in state', () => {
+    const ACTION_TYPE = 'TEST_ACTION'
+
+    const initialState = {
+      a: 0,
+    }
+
+    const badValue = new Map()
+
+    const reducer: Reducer = (state = initialState, action) => {
+      switch (action.type) {
+        case ACTION_TYPE: {
+          return {
+            a: badValue,
+          }
+        }
+        default:
+          return state
+      }
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware()
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: ACTION_TYPE })
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `A non-serializable value was detected in the state, in the path: \`testSlice.a\`. Value:`,
+      badValue,
+      `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+    )
+  })
+
+  describe('consumer tolerated structures', () => {
+    const nonSerializableValue = new Map()
+
+    const nestedSerializableObjectWithBadValue = {
+      isSerializable: true,
+      entries: (): [string, any][] => [
+        ['good-string', 'Good!'],
+        ['good-number', 1337],
+        ['bad-map-instance', nonSerializableValue],
+      ],
+    }
+
+    const serializableObject = {
+      isSerializable: true,
+      entries: (): [string, any][] => [
+        ['first', 1],
+        ['second', 'B!'],
+        ['third', nestedSerializableObjectWithBadValue],
+      ],
+    }
+
+    it('Should log an error when a non-serializable value is nested in state', () => {
+      const ACTION_TYPE = 'TEST_ACTION'
+
+      const initialState = {
+        a: 0,
+      }
+
+      const reducer: Reducer = (state = initialState, action) => {
+        switch (action.type) {
+          case ACTION_TYPE: {
+            return {
+              a: serializableObject,
+            }
+          }
+          default:
+            return state
+        }
+      }
+
+      // use default options
+      const serializableStateInvariantMiddleware =
+        createSerializableStateInvariantMiddleware()
+
+      const store = configureStore({
+        reducer: {
+          testSlice: reducer,
+        },
+        middleware: () => new Tuple(serializableStateInvariantMiddleware),
+      })
+
+      store.dispatch({ type: ACTION_TYPE })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      // since default options are used, the `entries` function in `serializableObject` will cause the error
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `A non-serializable value was detected in the state, in the path: \`testSlice.a.entries\`. Value:`,
+        serializableObject.entries,
+        `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+      )
+    })
+
+    it('Should use consumer supplied isSerializable and getEntries options to tolerate certain structures', () => {
+      const ACTION_TYPE = 'TEST_ACTION'
+
+      const initialState = {
+        a: 0,
+      }
+
+      const isSerializable = (val: any): boolean =>
+        val.isSerializable || isPlain(val)
+      const getEntries = (val: any): [string, any][] =>
+        val.isSerializable ? val.entries() : Object.entries(val)
+
+      const reducer: Reducer = (state = initialState, action) => {
+        switch (action.type) {
+          case ACTION_TYPE: {
+            return {
+              a: serializableObject,
+            }
+          }
+          default:
+            return state
+        }
+      }
+
+      const serializableStateInvariantMiddleware =
+        createSerializableStateInvariantMiddleware({
+          isSerializable,
+          getEntries,
+        })
+
+      const store = configureStore({
+        reducer: {
+          testSlice: reducer,
+        },
+        middleware: () => new Tuple(serializableStateInvariantMiddleware),
+      })
+
+      store.dispatch({ type: ACTION_TYPE })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      // error reported is from a nested class instance, rather than the `entries` function `serializableObject`
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `A non-serializable value was detected in the state, in the path: \`testSlice.a.third.bad-map-instance\`. Value:`,
+        nonSerializableValue,
+        `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+      )
+    })
+  })
+
+  it('Should use the supplied isSerializable function to determine serializability', () => {
+    const ACTION_TYPE = 'TEST_ACTION'
+
+    const initialState = {
+      a: 0,
+    }
+
+    const badValue = new Map()
+
+    const reducer: Reducer = (state = initialState, action) => {
+      switch (action.type) {
+        case ACTION_TYPE: {
+          return {
+            a: badValue,
+          }
+        }
+        default:
+          return state
+      }
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: () => true,
+      })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: ACTION_TYPE })
+
+    // Supplied 'isSerializable' considers all values serializable, hence
+    // no error logging is expected:
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+  })
+
+  it('should not check serializability for ignored action types', () => {
+    let numTimesCalled = 0
+
+    const serializableStateMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: () => {
+          numTimesCalled++
+          return true
+        },
+        ignoredActions: ['IGNORE_ME'],
+      })
+
+    const store = configureStore({
+      reducer: () => ({}),
+      middleware: () => new Tuple(serializableStateMiddleware),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'IGNORE_ME' })
+
+    // The state check only calls `isSerializable` once
+    expect(numTimesCalled).toBe(1)
+
+    store.dispatch({ type: 'ANY_OTHER_ACTION' })
+
+    // Action checks call `isSerializable` 2+ times when enabled
+    expect(numTimesCalled).toBeGreaterThanOrEqual(3)
+  })
+
+  describe('ignored action paths', () => {
+    function reducer() {
+      return 0
+    }
+    const nonSerializableValue = new Map()
+
+    it('default value: meta.arg', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(createSerializableStateInvariantMiddleware()),
+      }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })
+
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    })
+
+    it('default value can be overridden', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(
+            createSerializableStateInvariantMiddleware({
+              ignoredActionPaths: [],
+            }),
+          ),
+      }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `A non-serializable value was detected in an action, in the path: \`meta.arg\`. Value:`,
+        nonSerializableValue,
+        `\nTake a look at the logic that dispatched this action: `,
+        { type: 'test', meta: { arg: nonSerializableValue } },
+        `\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,
+        `\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,
+      )
+    })
+
+    it('can specify (multiple) different values', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(
+            createSerializableStateInvariantMiddleware({
+              ignoredActionPaths: ['payload', 'meta.arg'],
+            }),
+          ),
+      }).dispatch({
+        type: 'test',
+        payload: { arg: nonSerializableValue },
+        meta: { arg: nonSerializableValue },
+      })
+
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    })
+
+    it('can specify regexp', () => {
+      configureStore({
+        reducer,
+        middleware: () =>
+          new Tuple(
+            createSerializableStateInvariantMiddleware({
+              ignoredActionPaths: [/^payload\..*$/],
+            }),
+          ),
+      }).dispatch({
+        type: 'test',
+        payload: { arg: nonSerializableValue },
+      })
+
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    })
+  })
+
+  it('allows ignoring actions entirely', () => {
+    let numTimesCalled = 0
+
+    const serializableStateMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: () => {
+          numTimesCalled++
+          return true
+        },
+        ignoreActions: true,
+      })
+
+    const store = configureStore({
+      reducer: () => ({}),
+      middleware: () => new Tuple(serializableStateMiddleware),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'THIS_DOESNT_MATTER' })
+
+    // `isSerializable` is called once for a state check
+    expect(numTimesCalled).toBe(1)
+
+    store.dispatch({ type: 'THIS_DOESNT_MATTER_AGAIN' })
+
+    expect(numTimesCalled).toBe(2)
+  })
+
+  it('should not check serializability for ignored slice names', () => {
+    const ACTION_TYPE = 'TEST_ACTION'
+
+    const initialState = {
+      a: 0,
+    }
+
+    const badValue = new Map()
+
+    const reducer: Reducer = (state = initialState, action) => {
+      switch (action.type) {
+        case ACTION_TYPE: {
+          return {
+            a: badValue,
+            b: {
+              c: badValue,
+              d: badValue,
+            },
+            e: { f: badValue },
+            g: {
+              h: badValue,
+              i: badValue,
+            },
+          }
+        }
+        default:
+          return state
+      }
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({
+        ignoredPaths: [
+          // Test for ignoring a single value
+          'testSlice.a',
+          // Test for ignoring a single nested value
+          'testSlice.b.c',
+          // Test for ignoring an object and its children
+          'testSlice.e',
+          // Test for ignoring based on RegExp
+          /^testSlice\.g\..*$/,
+        ],
+      })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: ACTION_TYPE })
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    // testSlice.b.d was not covered in ignoredPaths, so will still log the error
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `A non-serializable value was detected in the state, in the path: \`testSlice.b.d\`. Value:`,
+      badValue,
+      `\nTake a look at the reducer(s) handling this action type: TEST_ACTION.
+(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,
+    )
+  })
+
+  it('allows ignoring state entirely', () => {
+    const badValue = new Map()
+    let numTimesCalled = 0
+    const reducer = () => badValue
+    const store = configureStore({
+      reducer,
+      middleware: () =>
+        new Tuple(
+          createSerializableStateInvariantMiddleware({
+            isSerializable: () => {
+              numTimesCalled++
+              return true
+            },
+            ignoreState: true,
+          }),
+        ),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'test' })
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    // Should be called twice for the action - there is an initial check for early returns, then a second and potentially 3rd for nested properties
+    expect(numTimesCalled).toBe(2)
+  })
+
+  it('never calls isSerializable if both ignoreState and ignoreActions are true', () => {
+    const badValue = new Map()
+    let numTimesCalled = 0
+    const reducer = () => badValue
+    const store = configureStore({
+      reducer,
+      middleware: () =>
+        new Tuple(
+          createSerializableStateInvariantMiddleware({
+            isSerializable: () => {
+              numTimesCalled++
+              return true
+            },
+            ignoreState: true,
+            ignoreActions: true,
+          }),
+        ),
+    })
+
+    expect(numTimesCalled).toBe(0)
+
+    store.dispatch({ type: 'TEST', payload: new Date() })
+    store.dispatch({ type: 'OTHER_THING' })
+
+    expect(numTimesCalled).toBe(0)
+  })
+
+  it('Should print a warning if execution takes too long', () => {
+    const reducer: Reducer = (state = 42, action) => {
+      return state
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({ warnAfter: 4 })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({
+      type: 'SOME_ACTION',
+      payload: new Array(10_000).fill({ value: 'more' }),
+    })
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      expect.stringMatching(
+        /^SerializableStateInvariantMiddleware took \d*ms, which is more than the warning threshold of 4ms./,
+      ),
+    )
+  })
+
+  it('Should not print a warning if "reducer" takes too long', () => {
+    const reducer: Reducer = (state = 42, action) => {
+      const started = Date.now()
+      while (Date.now() - started < 8) {}
+      return state
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({ warnAfter: 4 })
+
+    const store = configureStore({
+      reducer: {
+        testSlice: reducer,
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    store.dispatch({ type: 'SOME_ACTION' })
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+  })
+
+  it('Should cache its results', () => {
+    let numPlainChecks = 0
+    const countPlainChecks = (x: any) => {
+      numPlainChecks++
+      return isPlain(x)
+    }
+
+    const serializableStateInvariantMiddleware =
+      createSerializableStateInvariantMiddleware({
+        isSerializable: countPlainChecks,
+      })
+
+    const store = configureStore({
+      reducer: (state = [], action) => {
+        if (action.type === 'SET_STATE') return action.payload
+        return state
+      },
+      middleware: () => new Tuple(serializableStateInvariantMiddleware),
+    })
+
+    const state = createNextState([], () =>
+      new Array(50).fill(0).map((x, i) => ({ i })),
+    )
+    expect(isNestedFrozen(state)).toBe(true)
+
+    store.dispatch({
+      type: 'SET_STATE',
+      payload: state,
+    })
+    expect(numPlainChecks).toBeGreaterThan(state.length)
+
+    numPlainChecks = 0
+    store.dispatch({ type: 'NOOP' })
+    expect(numPlainChecks).toBeLessThan(10)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/tests/utils/CustomMatchers.d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/utils/CustomMatchers.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/utils/CustomMatchers.d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,16 @@
+import type { Assertion, AsymmetricMatchersContaining } from 'vitest'
+
+interface CustomMatchers<R = unknown> {
+  toMatchSequence(...matchers: Array<(arg: any) => boolean>): R
+}
+
+declare module 'vitest' {
+  interface Assertion<T = any> extends CustomMatchers<T> {}
+  interface AsymmetricMatchersContaining extends CustomMatchers {}
+}
+
+declare global {
+  namespace jest {
+    interface Matchers<R> extends CustomMatchers<R> {}
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/tests/utils/helpers.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/tests/utils/helpers.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tests/utils/helpers.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,217 @@
+import type {
+  EnhancedStore,
+  Middleware,
+  Reducer,
+  Store,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+import { setupListeners } from '@reduxjs/toolkit/query'
+import { useCallback, useEffect, useRef } from 'react'
+
+import { Provider } from 'react-redux'
+
+import { act, cleanup } from '@testing-library/react'
+
+export const ANY = 0 as any
+
+export const DEFAULT_DELAY_MS = 150
+
+export const getSerializedHeaders = (headers: Headers = new Headers()) => {
+  const result: Record<string, string> = {}
+  headers.forEach((val, key) => {
+    result[key] = val
+  })
+  return result
+}
+
+export async function waitMs(time = DEFAULT_DELAY_MS) {
+  const now = Date.now()
+  while (Date.now() < now + time) {
+    await new Promise((res) => process.nextTick(res))
+  }
+}
+
+export function waitForFakeTimer(time = DEFAULT_DELAY_MS) {
+  return new Promise((resolve) => setTimeout(resolve, time))
+}
+
+export function withProvider(store: Store<any>) {
+  return function Wrapper({ children }: any) {
+    return <Provider store={store}>{children}</Provider>
+  }
+}
+
+export const hookWaitFor = async (cb: () => void, time = 2000) => {
+  const startedAt = Date.now()
+
+  while (true) {
+    try {
+      cb()
+      return true
+    } catch (e) {
+      if (Date.now() > startedAt + time) {
+        throw e
+      }
+      await act(async () => {
+        await waitMs(2)
+      })
+    }
+  }
+}
+export const fakeTimerWaitFor = async (cb: () => void, time = 2000) => {
+  const startedAt = Date.now()
+
+  while (true) {
+    try {
+      cb()
+      return true
+    } catch (e) {
+      if (Date.now() > startedAt + time) {
+        throw e
+      }
+      await act(async () => {
+        await vi.advanceTimersByTimeAsync(2)
+      })
+    }
+  }
+}
+
+export const useRenderCounter = () => {
+  const countRef = useRef(0)
+
+  useEffect(() => {
+    countRef.current += 1
+  })
+
+  useEffect(() => {
+    return () => {
+      countRef.current = 0
+    }
+  }, [])
+
+  return useCallback(() => countRef.current, [])
+}
+
+expect.extend({
+  toMatchSequence(
+    _actions: UnknownAction[],
+    ...matchers: Array<(arg: any) => boolean>
+  ) {
+    const actions = _actions.concat()
+    actions.shift() // remove INIT
+
+    for (let i = 0; i < matchers.length; i++) {
+      if (!matchers[i](actions[i])) {
+        return {
+          message: () =>
+            `Action ${actions[i].type} does not match sequence at position ${i}.
+All actions:
+${actions.map((a) => a.type).join('\n')}`,
+          pass: false,
+        }
+      }
+    }
+    return {
+      message: () => `All actions match the sequence.`,
+      pass: true,
+    }
+  },
+})
+
+export const actionsReducer = {
+  actions: (state: UnknownAction[] = [], action: UnknownAction) => {
+    // As of 2.0-beta.4, we are going to ignore all `subscriptionsUpdated` actions in tests
+    if (action.type.includes('subscriptionsUpdated')) {
+      return state
+    }
+
+    return [...state, action]
+  },
+}
+
+export function setupApiStore<
+  A extends {
+    reducerPath: 'api'
+    reducer: Reducer<any, any>
+    middleware: Middleware
+    util: { resetApiState(): any }
+  },
+  R extends Record<string, Reducer<any, any>> = Record<never, never>,
+>(
+  api: A,
+  extraReducers?: R,
+  options: {
+    withoutListeners?: boolean
+    withoutTestLifecycles?: boolean
+    middleware?: {
+      prepend?: Middleware[]
+      concat?: Middleware[]
+    }
+  } = {},
+) {
+  const { middleware } = options
+  const getStore = () =>
+    configureStore({
+      reducer: { api: api.reducer, ...extraReducers },
+      middleware: (gdm) => {
+        const tempMiddleware = gdm({
+          serializableCheck: false,
+          immutableCheck: false,
+        }).concat(api.middleware)
+
+        return tempMiddleware
+          .concat(middleware?.concat ?? [])
+          .prepend(middleware?.prepend ?? []) as typeof tempMiddleware
+      },
+      enhancers: (gde) =>
+        gde({
+          autoBatch: false,
+        }),
+    })
+
+  type State = {
+    api: ReturnType<A['reducer']>
+  } & {
+    [K in keyof R]: ReturnType<R[K]>
+  }
+  type StoreType = EnhancedStore<
+    {
+      api: ReturnType<A['reducer']>
+    } & {
+      [K in keyof R]: ReturnType<R[K]>
+    },
+    UnknownAction,
+    ReturnType<typeof getStore> extends EnhancedStore<any, any, infer M>
+      ? M
+      : never
+  >
+
+  const initialStore = getStore() as StoreType
+  const refObj = {
+    api,
+    store: initialStore,
+    wrapper: withProvider(initialStore),
+  }
+  let cleanupListeners: () => void
+
+  if (!options.withoutTestLifecycles) {
+    beforeEach(() => {
+      const store = getStore() as StoreType
+      refObj.store = store
+      refObj.wrapper = withProvider(store)
+      if (!options.withoutListeners) {
+        cleanupListeners = setupListeners(store.dispatch)
+      }
+    })
+    afterEach(() => {
+      cleanup()
+      if (!options.withoutListeners) {
+        cleanupListeners()
+      }
+      refObj.store.dispatch(api.util.resetApiState())
+    })
+  }
+
+  return refObj
+}
Index: node_modules/@reduxjs/toolkit/src/tsHelpers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,223 @@
+import type { Middleware, StoreEnhancer } from 'redux'
+import type { Tuple } from './utils'
+
+export function safeAssign<T extends object>(
+  target: T,
+  ...args: Array<Partial<NoInfer<T>>>
+) {
+  Object.assign(target, ...args)
+}
+
+/**
+ * return True if T is `any`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+export type IsAny<T, True, False = never> =
+  // test if we are going the left AND right path in the condition
+  true | false extends (T extends never ? true : false) ? True : False
+
+export type CastAny<T, CastTo> = IsAny<T, CastTo, T>
+
+/**
+ * return True if T is `unknown`, otherwise return False
+ * taken from https://github.com/joonhocho/tsdef
+ *
+ * @internal
+ */
+export type IsUnknown<T, True, False = never> = unknown extends T
+  ? IsAny<T, False, True>
+  : False
+
+export type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>
+
+/**
+ * @internal
+ */
+export type IfMaybeUndefined<P, True, False> = [undefined] extends [P]
+  ? True
+  : False
+
+/**
+ * @internal
+ */
+export type IfVoid<P, True, False> = [void] extends [P] ? True : False
+
+/**
+ * @internal
+ */
+export type IsEmptyObj<T, True, False = never> = T extends any
+  ? keyof T extends never
+    ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>>
+    : False
+  : never
+
+/**
+ * returns True if TS version is above 3.5, False if below.
+ * uses feature detection to detect TS version >= 3.5
+ * * versions below 3.5 will return `{}` for unresolvable interference
+ * * versions above will return `unknown`
+ *
+ * @internal
+ */
+export type AtLeastTS35<True, False> = [True, False][IsUnknown<
+  ReturnType<<T>() => T>,
+  0,
+  1
+>]
+
+/**
+ * @internal
+ */
+export type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<
+  IsUnknown<T, True, False>,
+  IsEmptyObj<T, True, IsUnknown<T, True, False>>
+>
+
+/**
+ * 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
+
+// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified
+export type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
+  infer Head,
+  ...infer Tail,
+]
+  ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]>
+  : Acc
+
+type ExtractDispatchFromMiddlewareTuple<
+  MiddlewareTuple extends readonly any[],
+  Acc extends {},
+> = MiddlewareTuple extends [infer Head, ...infer Tail]
+  ? ExtractDispatchFromMiddlewareTuple<
+      Tail,
+      Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})
+    >
+  : Acc
+
+export type ExtractDispatchExtensions<M> =
+  M extends Tuple<infer MiddlewareTuple>
+    ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}>
+    : M extends ReadonlyArray<Middleware>
+      ? ExtractDispatchFromMiddlewareTuple<[...M], {}>
+      : never
+
+type ExtractStoreExtensionsFromEnhancerTuple<
+  EnhancerTuple extends readonly any[],
+  Acc extends {},
+> = EnhancerTuple extends [infer Head, ...infer Tail]
+  ? ExtractStoreExtensionsFromEnhancerTuple<
+      Tail,
+      Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})
+    >
+  : Acc
+
+export type ExtractStoreExtensions<E> =
+  E extends Tuple<infer EnhancerTuple>
+    ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}>
+    : E extends ReadonlyArray<StoreEnhancer>
+      ? UnionToIntersection<
+          E[number] extends StoreEnhancer<infer Ext>
+            ? Ext extends {}
+              ? IsAny<Ext, {}, Ext>
+              : {}
+            : {}
+        >
+      : never
+
+type ExtractStateExtensionsFromEnhancerTuple<
+  EnhancerTuple extends readonly any[],
+  Acc extends {},
+> = EnhancerTuple extends [infer Head, ...infer Tail]
+  ? ExtractStateExtensionsFromEnhancerTuple<
+      Tail,
+      Acc &
+        (Head extends StoreEnhancer<any, infer StateExt>
+          ? IsAny<StateExt, {}, StateExt>
+          : {})
+    >
+  : Acc
+
+export type ExtractStateExtensions<E> =
+  E extends Tuple<infer EnhancerTuple>
+    ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}>
+    : E extends ReadonlyArray<StoreEnhancer>
+      ? UnionToIntersection<
+          E[number] extends StoreEnhancer<any, infer StateExt>
+            ? StateExt extends {}
+              ? IsAny<StateExt, {}, StateExt>
+              : {}
+            : {}
+        >
+      : never
+
+/**
+ * Helper type. Passes T out again, but boxes it in a way that it cannot
+ * "widen" the type by accident if it is a generic that should be inferred
+ * from elsewhere.
+ *
+ * @internal
+ */
+export type NoInfer<T> = [T][T extends any ? 0 : never]
+
+export type NonUndefined<T> = T extends undefined ? never : T
+
+export type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &
+  Required<Pick<T, K>>
+
+export type WithOptionalProp<T, K extends keyof T> = Omit<T, K> &
+  Partial<Pick<T, K>>
+
+export interface TypeGuard<T> {
+  (value: any): value is T
+}
+
+export interface HasMatchFunction<T> {
+  match: TypeGuard<T>
+}
+
+export const hasMatchFunction = <T>(
+  v: Matcher<T>,
+): v is HasMatchFunction<T> => {
+  return v && typeof (v as HasMatchFunction<T>).match === 'function'
+}
+
+/** @public */
+export type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>
+
+/** @public */
+export type ActionFromMatcher<M extends Matcher<any>> =
+  M extends Matcher<infer T> ? T : never
+
+export type Id<T> = { [K in keyof T]: T[K] } & {}
+
+export type Tail<T extends any[]> = T extends [any, ...infer Tail]
+  ? Tail
+  : never
+
+export type UnknownIfNonSpecific<T> = {} extends T ? unknown : T
+
+/**
+ * A Promise that will never reject.
+ * @see https://github.com/reduxjs/redux-toolkit/issues/4101
+ */
+export type SafePromise<T> = Promise<T> & {
+  __linterBrands: 'SafePromise'
+}
+
+/**
+ * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).
+ */
+export function asSafePromise<Resolved, Rejected>(
+  promise: Promise<Resolved>,
+  fallback: (error: unknown) => Rejected,
+) {
+  return promise.catch(fallback) as SafePromise<Resolved | Rejected>
+}
Index: node_modules/@reduxjs/toolkit/src/uncheckedindexed.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/uncheckedindexed.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/uncheckedindexed.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,16 @@
+// inlined from https://github.com/EskiMojo14/uncheckedindexed
+// relies on remaining as a TS file, not .d.ts
+type IfMaybeUndefined<T, True, False> = [undefined] extends [T] ? True : False
+
+const testAccess = ({} as Record<string, 0>)['a']
+
+export type IfUncheckedIndexedAccess<True, False> = IfMaybeUndefined<
+  typeof testAccess,
+  True,
+  False
+>
+
+export type UncheckedIndexedAccess<T> = IfUncheckedIndexedAccess<
+  T | undefined,
+  T
+>
Index: node_modules/@reduxjs/toolkit/src/utils.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/utils.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,125 @@
+import { createNextState, isDraftable } from './immerImports'
+
+export function getTimeMeasureUtils(maxDelay: number, fnName: string) {
+  let elapsed = 0
+  return {
+    measureTime<T>(fn: () => T): T {
+      const started = Date.now()
+      try {
+        return fn()
+      } finally {
+        const finished = Date.now()
+        elapsed += finished - started
+      }
+    },
+    warnIfExceeded() {
+      if (elapsed > maxDelay) {
+        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. 
+If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
+It is disabled in production builds, so you don't need to worry about that.`)
+      }
+    },
+  }
+}
+
+export function delay(ms: number) {
+  return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+export class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<
+  Items[number]
+> {
+  constructor(length: number)
+  constructor(...items: Items)
+  constructor(...items: any[]) {
+    super(...items)
+    Object.setPrototypeOf(this, Tuple.prototype)
+  }
+
+  static override get [Symbol.species]() {
+    return Tuple as any
+  }
+
+  override concat<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: Tuple<AdditionalItems>,
+  ): Tuple<[...Items, ...AdditionalItems]>
+  override concat<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: AdditionalItems,
+  ): Tuple<[...Items, ...AdditionalItems]>
+  override concat<AdditionalItems extends ReadonlyArray<unknown>>(
+    ...items: AdditionalItems
+  ): Tuple<[...Items, ...AdditionalItems]>
+  override concat(...arr: any[]) {
+    return super.concat.apply(this, arr)
+  }
+
+  prepend<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: Tuple<AdditionalItems>,
+  ): Tuple<[...AdditionalItems, ...Items]>
+  prepend<AdditionalItems extends ReadonlyArray<unknown>>(
+    items: AdditionalItems,
+  ): Tuple<[...AdditionalItems, ...Items]>
+  prepend<AdditionalItems extends ReadonlyArray<unknown>>(
+    ...items: AdditionalItems
+  ): Tuple<[...AdditionalItems, ...Items]>
+  prepend(...arr: any[]) {
+    if (arr.length === 1 && Array.isArray(arr[0])) {
+      return new Tuple(...arr[0].concat(this))
+    }
+    return new Tuple(...arr.concat(this))
+  }
+}
+
+export function freezeDraftable<T>(val: T) {
+  return isDraftable(val) ? createNextState(val, () => {}) : val
+}
+
+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 function promiseWithResolvers<T>(): {
+  promise: Promise<T>
+  resolve: (value: T | PromiseLike<T>) => void
+  reject: (reason?: any) => void
+} {
+  let resolve: any
+  let reject: any
+  const promise = new Promise<T>((res, rej) => {
+    resolve = res
+    reject = rej
+  })
+  return { promise, resolve, reject }
+}
